它可以帮助需要注意的是函数闭基本上等同于懒惰值:
lazy n : 'a Lazy.t <=> (fun() -> n) : unit -> 'a
force x : 'a <=> x() : 'a
所以类型'a llist
相当于
type 'a llist = 'a cell Lazy.t
即,一个懒惰的单元格的值。
的地图实现可能更有意义上述定义
let rec map f lst =
match force lst with
| Nil -> lazy Nil
| Cons (hd,tl) -> lazy (Cons (f hd, map f tl))
翻译的术语,其放回关闭:
let rec map f lst =
match lst() with
| Nil -> (fun() -> Nil)
| Cons (hd,tl) -> (fun() -> Cons (f hd, map f tl))
与追加
同样
let rec append a b =
match force a with
| Nil -> b
| Cons (hd,tl) -> lazy (Cons (hd, append tl b))
变得
let rec append a b =
match a() with
| Nil -> b
| Cons (hd,tl) -> (fun() -> Cons (hd, append tl b))
我通常更喜欢使用lazy
语法,因为它使得它更清楚发生了什么。
请注意,还有一个懒惰悬挂和关闭不是正好等效。例如,
let x = lazy (print_endline "foo") in
force x;
force x
打印
foo
而
let x = fun() -> print_endline "foo" in
x();
x()
打印
foo
foo
的区别在于force
计算表达式的值恰好一次。