比较函数的惰性组合

lazy composition of compare functions

我想编写几个compare函数应用程序。一个天真的方法是:

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

但是,所有这些都将被评估,即使第一个 returns 0 并且不需要进一步评估。如果有办法懒惰地执行此操作,最好保留中缀语法?

由于 OCaml 是一种急切的语言,因此函数的参数在函数调用之前进行评估。您希望延迟计算 >>== 函数的第二个参数,而获得此参数的唯一方法几乎是使用 lambda 或等效的内置延迟支持。

你可以这样写你的函数:

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)

可能有更优雅的方式来设置定义,但我相信这是基本问题。