Hi. I’m learning OCaml. I did most of the tutorials on ocaml.org, and now I’m reading Real World OCaml. At first, I thought it was weird to use an alternative standard library, but I generally appreciate the design of Base
a little more than Pervasives
, especially the preference for result variants over exceptions.
Anyway, before I started using Base
, I was playing with Seq
, which I like. As one does, I tried using it to implement infinite lazy Fibonacci. It was easy enough:
let rec fibs a b = fun () -> Seq.Cons(a, fibs b (a+b))
let fibs = fibs 0 1
*I realize that should be bigints for “production Fibonacci.”
Anyway, after I started using Base
, I was getting warnings about not using stuff from Pervasives
directly, so I took a look to see what Base’s alternative is to Seq
. I found Sequence
. It doesn’t appear to be similar to Seq
at all, and I was unable to divine its proper usage from the the documentation. I gather than Sequence.Step
must somehow be involved, but I’m not really sure what to do there, or maybe it’s done with Sequence.unfold_step
?
So, I looked at the code of the module itself and eventually figured out maybe it needs to be something like this:
let rec fibs a b =
Sequence.unfold_step ~init:(a, b)
~f:(fun (a, b) ->
Sequence.Step.Yield(a, (b, a+b)));;
This works, in any case, and I guess I understand how, but I’m not used to reading the implementation of a library in order to understand how to use the interface. While there is obviously a lot of benefit to reading the code you use, the difficulty at this point in learning OCaml is that I end up seeing a lot of things I don’t understand.
For example:
type +_ t =
| Sequence : 's * ('s -> ('a,'s) Step.t) -> 'a t
Not really clear on what +_
means or what :
means in the definition of a constructor (being accustomed to of
). I think this has something to GADTs, but I haven’t gotten that far in the book yet and, though I’ve peaked ahead, I really have no idea what all that is about. Which is fine. I’ll get there when I get there.
I’m just wondering if this is the normal way to learn OCaml libraries or if there is a better way.