转载自: http://en.wikipedia.org/wiki/Lazy_evaluation

In programming language theorylazy evaluation or call-by-needcitation needed]

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 data structures
  • The capability of defining control structures 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*x
set 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 c
l = 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[12] 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[13] 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.

相关文章: