Ocaml modules implementation

孤者浪人 提交于 2019-12-12 08:28:15

问题


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?


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3982731/ocaml-modules-implementation

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