转载自:
In , lazy evaluation or call-by-need is an which delays the evaluation of an expression until the value of this is actually required () and which also avoids repeated evaluations (). The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as .[]
The benefits of lazy evaluation include:
- Performance increases due to avoiding unnecessary calculations and avoiding error conditions in the evaluation of compound expressions.
- The capability of constructing potentially infinite
- The capability of defining as abstractions instead of as primitives.
In most eager languages, if statements evaluate in a lazy fashion.
if a then b else c
evaluates (a), then if and only if (a) evaluates to true does it evaluate (b), otherwise it evaluates (c). That is, either (b) or (c) will not be evaluated. Conversely, in an eager language the expected behavior is that
define f(x,y) = 2*xset k = f(e,5)
will still evaluate (e) and (f) when computing (k). However, user-defined control structures depend on exact syntax, so for example
define g(a,b,c) = if a then b else cl = g(h,i,j)
(i) and (j) would both be evaluated in an eager language. While in
l' = if h then i else j
(i) or (j) would be evaluated, but never both.
Laziness in eager languages
Python: In Python 2.x the range()
function computes a list of integers (eager or immediate evaluation):
>>> r = range(10) >>> print r [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print r[3] 3
In Python 3.x the range()
function returns an iterator which computes elements of the list on demand (lazy or deferred evaluation):
>>> r = range(10) >>> print(r) range(0, 10) >>> print(r[3]) 3
- This change to lazy evaluation saves execution time for large ranges which may never be fully referenced and memory usage for large ranges where only one or a few elements are needed at any time.