IEnumerable <T> in OCaml
I use F # a lot. All the basic collections in F # implement the IEumberable interface, so itโs quite natural to access them using the only Seq module in F #. Is this possible in OCaml?
Another question is that 'a seq in F # is lazy, for example. I can create a sequence from 1 to 100 using {1..100} or in more detail:
seq { for i=1 to 100 do yield i } In OCaml, I use the following two methods to work with this function:
generate a list:
let rec range ab = if a > b then [] else a :: range (a+1) b;;or resort to explicit recursive functions.
The first generates additional lists. The second breaks the abstraction because I need to work at the sequence level using higher-order functions like map and fold .
I know that the OCaml library has a Stream module. But its functionality is apparently quite limited, and not generally like 'a seq in F #.
By the way, I play Project Euler using OCaml. Thus, there are quite a few operations with sequences that in an imperative language there will be cycles with a complex body.
This Ocaml library seems to offer what you are asking for. I have not used it, though.
http://batteries.forge.ocamlcore.org/
Checkout this module, Enum http://batteries.forge.ocamlcore.org/doc.preview:batteries-beta1/html/api/Enum.html
I somehow feel that Enum is much better than Seq. It eliminates lowercase / uppercase slowdown in Seqs.
The enumerator, visible from the functional angle of programming, is precisely the fold function. If the class implements the Enumerable interface in an object-oriented library of data structures, the type comes with the fold function in the library of the functional data structure.
Stream is a slightly bizarre imperative lazy list (the imperative is that reading an element is destructive). CamlP5 comes with a lazy-list functional library, Fstream . This already cited stream offers several alternatives .
The mentioned Batteries library also has an operator (-):
# 1 -- 100;; - : int BatEnum.t = <abstr> Enumeration is not evaluated until you cross elements, so it provides a function similar to your second query. Just be careful that Batteries' enum are mutable. Ideally, there would also be an implementation of a lazy list in which all data structures could be converted to / from, but this work has not yet been completed.