Ocaml 比较函数的惰性合成
我想编写几个Ocaml 比较函数的惰性合成,ocaml,lazy-evaluation,Ocaml,Lazy Evaluation,我想编写几个比较函数应用程序。天真的做法是: let (>>==): int -> int -> int = fun a b -> if a = 0 then 0 else b type c = {f1 : bool; f2: int; f3: bool; f4: int; unused: int} let compare (a:c) (b:c) = compare a.f1 b.f1 >>== compare a.f2 b.f2 &
比较函数应用程序。天真的做法是:
let (>>==): int -> int -> int = fun a b -> if a = 0 then 0 else b
type c = {f1 : bool; f2: int; f3: bool; f4: int; unused: int}
let compare (a:c) (b:c) =
compare a.f1 b.f1 >>==
compare a.f2 b.f2 >>==
compare a.f3 b.f3 >>==
compare a.f4 b.f4
但是,即使第一个返回0,并且不需要进一步求值,也将对所有这些值进行求值。如果有一种方法可以惰性地执行此操作,最好保留中缀语法?因为OCaml是一种渴望的语言,函数的参数在函数调用之前进行求值。您希望对>>==
函数的第二个参数进行惰性计算,而实现这一点的唯一方法是使用lambdas或等效的内置惰性支持
您可以这样编写函数:
let (>>==) a bl =
if a = 0 then 0 else bl ()
let lcompare (a:c) (b:c) =
compare a.f1 b.f1 >>==
(fun () -> compare a.f2 b.f2) >>==
(fun () -> compare a.f3 b.f3) >>==
(fun () -> compare a.f4 b.f4)
这样称呼它:
let (>>==) a bl =
if a = 0 then 0 else bl ()
let lcompare (a:c) (b:c) =
compare a.f1 b.f1 >>==
(fun () -> compare a.f2 b.f2) >>==
(fun () -> compare a.f3 b.f3) >>==
(fun () -> compare a.f4 b.f4)
或者,您可以使用内置的惰性功能:
let (>>==) a bl =
if a = 0 then 0 else Lazy.force bl
let lcompare (a:c) (b:c) =
compare a.f1 b.f1 >>==
lazy (compare a.f2 b.f2) >>==
lazy (compare a.f3 b.f3) >>==
lazy (compare a.f4 b.f4)
也许有一种更优雅的方式来定义,但我相信这是最基本的问题