I’m just beginning F# so please be kind if this is basic.
I’ve read that a function marked lazy is evaluated only once and then cached. For example:
let lazyFunc = lazy (1 + 1)
let theValue = Lazy.force lazyFunc
Compared to this version which would actually run each time it’s called:
let eagerFunc = (1 + 1)
let theValue = eagerFunc
Based on that, should all functions be made lazy? When would you not want to? This is coming from material in the book “Beginning F#”.
First of all, it may be helpful to note that none of the things you have defined is a function –
eagerFuncandtheValueare values of typeintandlazyFuncis a value of typeLazy<int>. Givenand
the expression
1 + 1will not be evaluated more than once no matter how many times you useeagerTwo. The difference is that1 + 1will be evaluated exactly once when definingeagerTwo, but will be evaluated at most once whenlazyTwois used (it will be evaluated the first time that theValueproperty is accessed, and then cached so that further uses ofValuedo not need to recalculated it). IflazyTwo‘sValueis never accessed, then its body1 + 1will never be evaluated.Typically, you won’t see much benefit to using lazy values in a strict language like F#. They add a small amount of overhead since accessing the
Valueproperty requires checking whether the value has already been calculated. They might save you a bit of calculation if you have something likelet lazyValue = lazy someVeryExpensiveCalculationThatMightNotBeNeeded(), since the expensive calculation will only take place if the value is actually used. They can also make some algorithms terminate which otherwise would not, but this is not a major issue in F#. For instance: