Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ocaml 比较函数的惰性合成_Ocaml_Lazy Evaluation - Fatal编程技术网

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)
也许有一种更优雅的方式来定义,但我相信这是最基本的问题