Search code examples
f#lazy-evaluation

Lazy<'T> vs anonymous functions


Is there any advantage to using the .NET lazy operator instead of a plain function?

For example:

let x = lazy ...
let y = lazy (1 + x.Value)

let x = (fun () -> ...)
let y = (fun () -> 1 + x())


Solution

  • The difference between a lazy value and a function is that a lazy value is evaluated only once. It then caches the result and accessing it again will not recalculate the value. A function is evaluated each time you call it.

    This has performance implications and it also matters when you have side effects. For example, the following prints "calculating x" just once:

    let x = lazy (printfn "calculating x"; 1)
    let y = lazy (1 + x.Value)
    y.Value + y.Value
    

    The following prints "calculating x" two times:

    let x = (fun () -> printfn "calculating x"; 1)
    let y = (fun () -> 1 + x())
    y () + y ()