The functional feature of lazy
computations in F# allows for delayed evaluations, that is, only compute when needed. This feature improves performance and prevents excessive computations when not needed:
let identifier = lazy ( expression )
The lazy
identifier in the preceding code delays the evaluation of an expression or contained code segment. Let's explain this with a simple example as seen in the following screenshot:
When the lazy
keyword is used, the expression is not evaluated immediately; the computation happens only when requested. This is not the case with a non-lazy expression where the value was calculated and printed right away. The value was evaluated and printed right away, albeit as needed, when we requested it as follows:
> x.Value ;;
Besides these primitive operations, there are more sophisticated data structures such as sequence cache and LazyList which are built using the lazy evaluation constructs. Unfortunately, F# lists are not lazy by default and LazyLists...