sth*_*55 1 ocaml functional-programming lazy-evaluation
我编写这个示例是为了更好地理解 OCaml 中惰性求值的工作原理 - 使用 thonks。
let rec imp n = fun () -> imp(n*n);;
Run Code Online (Sandbox Code Playgroud)
我对惰性求值/thonks 的理解是, impl 会按照我调用的频率对初始数字进行平方
imp ()。
然而这个函数imp会引发以下错误:
---
let rec imp n acc = fun()->(***imp (n\*acc)***);;
This expression has type int -> unit -> 'a
but an expression was expected of type 'a
The type variable 'a occurs inside int -> unit -> 'a
---
Run Code Online (Sandbox Code Playgroud)
编译器告诉您您的函数具有递归类型。-rectypes如果您在运行时提供,则可以使用递归类型ocaml:
$ ocaml -rectypes
OCaml version 4.10.0
# let rec imp n = fun () -> imp(n*n);;
val imp : int -> (unit -> 'a as 'a) = <fun>
Run Code Online (Sandbox Code Playgroud)
另一方面,我认为你的功能并不像你想象的那样工作。或者至少我看不到任何方法来找出它最近计算出的数字。我猜你必须相信它正在计算越来越大的数字。