Most programming languages, including F#, evaluate computations immediately in accord with a model called Strict Evaluation. However, in Lazy Evaluation, computations are not evaluated until they are needed. F# allows us to use lazy evaluation through both the lazy
keyword and sequences
.
// define a lazy computation
let comp = lazy(10 + 20)
// we need to force the result
let ans = comp.Force()
In addition, when using Lazy Evaluation, the results of the computation are cached so if we force the result after our first instance of forcing it, the expression itself won't be evaluated again
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()