In Python map() works on any data that follows the sequence protocol. It does The Right Thing^TM whether I feed it a string or a list or even a tuple.
Can't I have my cake in OCaml too? Do I really have no other choice but to look at the collection type I'm using and find a corresponding List.map or an Array.map or a Buffer.map or a String.map? Some of these don't even exist! Is what I'm asking for unusual? I must be missing something.
The closest you will get to this is the module Enum
in OCaml Batteries Included (formerly of Extlib). Enum
defines maps and folds over Enum.t
; you just have to use a conversion to/from Enum.t
for your datatype. The conversions can be fairly light-weight, because Enum.t
is lazy.
What you really want is Haskell-style type classes, like Foldable
and Functor
(which generalizes "maps"). The Haskell libraries define instances of Foldable
and Functor
for lists, arrays, and trees. Another relevant technique is the "Scrap Your Boilerplate" approach to generic programming. Since OCaml doesn't support type classes or higher-kinded polymorphism, I don't think you'd be able to express patterns like these in its type system.