ocaml - `Lazy.force` 和 `Lazy.force_val` 之间的区别

标签 ocaml lazy-evaluation

Lazy 模块中有两种力量:

val force : 'a t -> 'a

force x forces the suspension x and returns its result. If x has already been forced, Lazy.force x returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. Raise Undefined if the forcing of x tries to force x itself recursively.



val force_val : 'a t -> 'a

force_val x forces the suspension x and returns its result. If x has already been forced, force_val x returns the same value again without recomputing it. Raise Undefined if the forcing of x tries to force x itself recursively. If the computation of x raises an exception, it is unspecified whether force_val x raises the same exception or Undefined.



似乎唯一的区别是

If the computation of x raises an exception, it is unspecified whether force_val x raises the same exception or Undefined.`



据我了解,我们不知道它是否会引发原始异常或 Undefined如果我们使用 force_val .

那么这背后的意义何在?为什么要这样?我们可以从 force_val 获得任何好处?

最佳答案

我想这是出于性能目的。
如果您关心得到相同的错误,请使用 force .如果您不想但想要更好的性能,请使用 force_val .

如您所见here , forceforce_val 做同样的事情但在发生异常时执行额外的内存访问。

阅读源代码并运行一些测试后,这两个函数的行为似乎与文档所说的不同:如果您只使用 force ,您将始终得到原始错误,但如果您使用 force_val第一次调用将引发原始异常以及对 force_val 的所有后续调用。 force 将提高Undefined .

编辑:实际上,我不确定使用 force_val而不是 forceforce 开始提高性能是原语和 force_val不是。

关于ocaml - `Lazy.force` 和 `Lazy.force_val` 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293234/

相关文章:

go - 在 Go 中为函数预计算简单值

OCaml 检查函数

ocaml - 在 OCaml 中的不可变记录或对象更新期间共享多少内存?

scala - 懒惰的scala理解评估

scala - @transient 惰性 val 字段序列化

pattern-matching - OCaml 中的 "as"关键字

mysql - 来自 mysql 的 ocaml 哈希

javascript - GetOrgChart - 插入Node而不直接扩展它

lazy-evaluation - 按需求调用与按名称调用

lazy-evaluation - let-in 在 Elm 中的绑定(bind)是惰性的吗?