Ocaml模块的实现 [英] Ocaml modules implementation
问题描述
Ocaml的标准库包含各种模块:List
,Map
,Nativeint
等.我知道提供了这些模块的接口(例如,
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.
在哪里可以找到?
推荐答案
- 在您的系统上:
/usr/lib/ocaml/list.ml
和其他.ml
文件 - 在网络上: https://github.com/ocaml /ocaml/blob/trunk/stdlib/list.ml 和
- 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
List实现很有趣,值得研究.例如,
map
函数可以这样实现: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
但是却是这样实现的:
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] ;;
第一个打印123,但是第二个打印321!由于对
f a
的求值可能会产生副作用,因此强制执行正确的顺序很重要.这就是官方地图的实现方式.实际上,在OCaml中未指定参数的评估顺序,即使所有实现都遵循相同的顺序.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.另请参见优化Jane Street博客上的List.map帖子以了解有关性能的注意事项(
List.map
在小列表上很有效).See also the Optimizing List.map post on the Jane Street blog for considerations on performance (
List.map
is efficient on small lists).这篇关于Ocaml模块的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- On your system: