Ocaml's standard library contains various modules: List
, Map
, Nativeint
, etc. I know that interfaces for these modules are provided (e.g. for the List module), but I am interested in the algorithms and their implementations used in modules' functions.
Where can I find that?
ocaml modules allow to package together data structures definitions and functions operating on them. This allow to reduce code size and name confusion, as any identifier can appear in different modules, with different meanings, without any interference.
The OCaml programming language does not have type classes but rather provides a construction called modules. Ad hoc polymorphism via Haskell-like typeclass style programming can be supported in OCaml by viewing type classes as a particular mode of use of modules.
A functor is a module that is parametrized by another module, just like a function is a value which is parametrized by other values, the arguments. It allows one to parametrize a type by a value, which is not possible directly in OCaml without functors.
Well, val is a keyword in OCaml with several different uses. The cases you mention are both, in essence, that val is used in a module signature to specify values that appear in the module. Values are things like functions and expressions.
/usr/lib/ocaml/list.ml
and other .ml
files.ml
files in https://github.com/ocaml/ocaml/tree/trunk/stdlib
The List implementation is interesting to study. For example, the map
function could be implemented like this:
let rec map f = function
| [] -> []
| a::l -> f a :: map f l
but is instead implemented like this:
let rec map f = function
| [] -> []
| a::l -> let r = f a in r :: map f l
What's the difference? Execute this:
List.map print_int [1;2;3] ;;
map print_int [1;2;3] ;;
The first one prints 123, but the second one prints 321! Since the evaluation of f a
could produce side effects, it's important to force the correct order. This is what the official map implementation does. Indeed, the evaluation order of arguments is unspecified in OCaml even if all implementations follow the same order.
See also the Optimizing List.map post on the Jane Street blog for considerations on performance (List.map
is efficient on small lists).
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