I use F# a lot. All the basic collections in F# implement IEumberable interface, thus it is quite natural to access them using the single Seq
module in F#. Is this possible in OCaml?
The other question is that 'a seq
in F# is lazy, e.g. I can create a sequence from 1
to 100
using {1..100}
or more verbosely:
seq { for i=1 to 100 do yield i }
In OCaml, I find myself using the following two methods to work around with this feature:
generate a list:
let rec range a b =
if a > b then []
else a :: range (a+1) b;;
or resort to explicit recursive functions.
The first generates extra lists. The second breaks the abstraction as I need to operate on the sequence level using higher order functions such as map
and fold
.
I know that the OCaml library has Stream module. But the functionality of it seems to be quite limited, not as general as 'a seq
in F#.
BTW, I am playing Project Euler problems using OCaml recently. So there are quite a few sequences operations, that in an imperative language would be loops with a complex body.
This Ocaml library seems to offer what you are asking. I've 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 Enum is a much better name than Seq. It eliminates the lowercase/uppercase confusion on Seqs.
An enumerator, seen from a functional programming angle, is exactly a fold
function. Where a class would implement an Enumerable
interface in an object-oriented data structures library, a type comes with a fold
function in a functional data structure library.
Stream
is a slightly quirky imperative lazy list (imperative in that reading an element is destructive). CamlP5 comes with a functional lazy list library, Fstream
. This already cited thread offers some alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With