ocaml Lazy 类型有一些魔力。我认为当你自己实现它时更容易理解惰性,虽然在语法上不方便但很容易。诀窍是
这里很清楚在 Lazy'.force 期间记忆是如何以及何时发生的。
module Lazy' : sig
type 'a t
val delay: (unit -> 'a) -> 'a t
val force: 'a t -> 'a
end = struct
type 'a susp =
| NotYet of (unit -> 'a)
| Done of 'a
type 'a t = 'a susp ref
let delay f = ref (NotYet f)
let force f =
match !f with
| Done x -> x
| NotYet f' ->
let a = f'() in
f := Done a;
a
end
type 'a stream = Cons of 'a * 'a stream Lazy'.t;;
let one = let rec one' () = Cons(1, Lazy'.delay one') in one' () ;;
让 rec 映射 fs = 匹配 s 与 | Cons(h, t) -> Cons(fh, Lazy'.delay (fun () -> map f(Lazy'.force t))) ;;