Call By Need Semantics

Replace all instances of a calculation with references to a single LazyObject. The calculation will only be made once even though it appears in the code several times.

The notion of LazyEvaluation can be extended so that the value of an expression is used interchangeably with the expression itself. This extension of LazyEvaluation and sharing the value of the evaluated expression is used to implement CallByNeed semantics.

In order for CallByNeed to work the expression must represent a relatively immutable value -- relative to the context in which the expression is to be used, that is. Pure FunctionalProgrammingLanguages ensure this condition by avoiding the use of state. Since there is no state there are no state changes that can invalidate the calculated result of an expression. Procedural languages can achieve the same effect by ensuring that the state depended upon by the expression doesn't change while the expression is in use. Combining LazyEvaluationAndTransactionSemantics is one way to achieve this. While any use of LazyEvaluation in a procedural environment will cause this problem it is exacerbated by CallByNeed semantics because the expression itself must be treated as an immutable value.

Because the same expression may be used multiple times and may be correctly applied to many different states it is useful to define instances of an expression and constrain the lifetimes of those instances to the contexts in which they are actually used. LazyObject is one way to implement CallByNeed semantics in an ObjectOrientedProgramming environment. LazyObjects are immutable ValueObjects that can be reused as long as they are valid and discarded once the state they depend on has changed.
CategoryObjectFunctionalPatterns CategoryLazyPattern

View edit of December 17, 2009 or FindPage with title or text search