F 中的懒惰评估简介

与大多数编程语言一样,F#默认使用严格评估。在严格评估中,立即执行计算。相比之下,Lazy Evaluation 推迟执行计算,直到需要它们的结果。此外,缓存评估下的计算结果被缓存,从而避免了对表达式的重新评估的需要。

我们可以通过 lazy 关键字和 Sequences 在 F#中使用 Lazy 评估

// 23 * 23 is not evaluated here
// lazy keyword creates lazy computation whose evaluation is deferred 
let x = lazy(23 * 23)

// we need to force the result
let y = x.Force()

// Hello World not printed here
let z = lazy(printfn "Hello World\n"; 23424)

// Hello World printed and 23424 returned
let ans1 = z.Force()

// Hello World not printed here as z as already been evaluated, but 23424 is
// returned
let ans2 = z.Force()