Call-by-need is a calling mechanism for purely functional programming languages. It is sometimes also called lazy evaluation.
It is a way of implementing call-by-name but 'memoising' (or sharing) the evaluated result of subexpressions, so they do not need to be re-evaluated every time they are encountered.
A version of call-by-need is implemented by the Haskell programming language.
In more detail, suppose the meaning of a variable (say of Boolean type) is not a value, but a thunk - a frozen computation that has not yet been run. Suppose we then have an expression that strictly relies on a variable x
, e.g.
let x = <long difficult computation> in
if x then ... x ... else ... x ...
where x
is a thunk that takes a long while to evaluate.
In order to pick which branch to evaluate, the language needs to know whether x
is the value True
or the value False
. This forces evaluation of the thunk pointed to by x
.
But either branch of the conditional construct may also use the value of x
. The idea is that, if a language is pure, then we can replace the thunk of x
by the value in memory, so that when we evaluate the then
or the else
branch, we do not need to run the expensive computation again.
[Launchbury 1993] gave an operational semantics of call-by-need, which is very close to describing the actual implementation. The semantics sequentially threads a global heap through execution. This allows for enough sharing.
[Ariola et al. 1995] showed how to reify this heap into the term itself, thereby building a rewrite system which is faithful to lazy evaluation.
Wikipedia has a number of historical claims which should be evaluated and transferred here at some point.
In particular, call-by-need seems to have been introduced by Chris Wadsworth in 1971.
Semantics of call-by-need:
John Launchbury. 1993. A natural semantics for lazy evaluation. In Proceedings of the 20th ACM SIGPLAN-SIGACT symposium on Principles of programming languages (POPL '93). Association for Computing Machinery, New York, NY, USA, 144–154. https://doi.org/10.1145/158511.158618
Zena M. Ariola, John Maraist, Martin Odersky, Matthias Felleisen, and Philip Wadler. 1995. A call-by-need lambda calculus. In Proceedings of the 22nd ACM SIGPLAN-SIGACT symposium on Principles of programming languages (POPL '95). Association for Computing Machinery, New York, NY, USA, 233–246. https://doi.org/10.1145/199448.199507