Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml modules implementation

Tags:

ocaml

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?

like image 673
Peter Avatar asked Oct 20 '10 22:10

Peter


People also ask

What are modules OCaml?

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.

Does OCaml have Typeclasses?

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.

What are Functors in OCaml?

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.

What is Val in OCaml?

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.


1 Answers

  • On your system: /usr/lib/ocaml/list.ml and other .ml files
  • On the web: https://github.com/ocaml/ocaml/blob/trunk/stdlib/list.ml and other .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).

like image 101
Quentin Pradet Avatar answered Sep 18 '22 20:09

Quentin Pradet