Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable<T> in OCaml

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:

  1. generate a list:

    let rec range a b = 
      if a > b then []
      else a :: range (a+1) b;;
    
  2. 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.

like image 762
Yin Zhu Avatar asked Jul 05 '11 23:07

Yin Zhu


2 Answers

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.

like image 197
Bala Avatar answered Sep 30 '22 14:09

Bala


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.

like image 32
Gilles 'SO- stop being evil' Avatar answered Sep 30 '22 12:09

Gilles 'SO- stop being evil'