Ocaml modules implementation

匆匆过客 提交于 2019-12-04 02:58:40

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).

You can find the definitions in the OCaml source code. For example, implementation of the Map functions is in stdlib/map.ml in the OCaml source distribution.

They should already be installed on your system. Most likely (assuming a Unix system) they are located in /usr/lib/ocaml or /usr/local/lib/ocaml. Just open any of the .ml files.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!