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()