懶惰評估簡介
大多數程式語言(包括 F#)都會根據稱為嚴格評估的模型立即評估計算。但是,在 Lazy Evaluation 中,計算直到需要時才會進行評估。F#允許我們通過 lazy 關鍵字和 sequences 使用延遲評估。
// define a lazy computation
let comp = lazy(10 + 20)
// we need to force the result
let ans = comp.Force()
此外,在使用 Lazy Evaluation 時,計算結果會被快取,因此如果我們在第一個強制例項後強制執行結果,則表示式本身將不再被計算
let rec factorial n = 
  if n = 0 then 
    1
  else 
    (factorial (n - 1)) * n
let computation = lazy(printfn "Hello World\n"; factorial 10)
// Hello World will be printed
let ans = computation.Force()
// Hello World will not be printed here
let ansAgain = computation.Force()