05.13.08
Batteries Included Preview: Enumerations
I have made available the first preview of a second module for OCaml Batteries Included module: Enum. This module builds upon ExtLib’s enumerations (which it means to replace, if it is accepted upstream) and provides support for representation-independent iterators. These iterators are used pervasively in ExtLib and will also be used pervasively in the rest of Batteries Included, as a manner of converting data from/to data structures and as a base for syntax extensions.
With respect to ExtLib’s current implementation, this release adds
- numerous powerful constructors and manipulation functions
- functions inspired from SDFlow and dedicated to cooperative
- better management of infinite iterators
- better management of iterators created using
from - syntactic sugar.
As an example of the last point, let us note that it is now possible, without any Camlp4 extension, to replace for loops with a more (stream-)functional counterpart. That is, instead of
for i = 1 to n do
(*...*)
done
one may now write
iter (fun i -> (* ... *) ) (5 -- 10)
for an imperative loop or
map (fun i -> (* ... *) ) (5 -- 10)
for a lazy transformation, etc. It won’t improve performance and it doesn’t look more readable at first glance, but it allows short expressions such as :
iter printf (5 -- 10) (*to print all numbers between 5 and 10*) map ( ~ ) (5 --10) (*to obtain enumeration -5, -6, -7, -8, -9, -10 *) fold ( + ) 0 ( 5 -- 10 )(*to sum all numbers between 5 and 10*)
etc. Everything is computed lazily, without allocating any intermediate data structure.
Code may be found here.