[转] Lazy evaluation

懒惰求值是一种程序设计策略,推迟表达式的计算直至其值真正需要时才进行,并且避免重复计算。它能够提高性能,避免不必要的计算,构建潜在无限的数据结构,并定义控制结构为抽象。懒惰求值在某些情况下能显著减少运行时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

In programming language theorylazy evaluation or call-by-need[1] is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required (non-strict evaluation) and which also avoids repeated evaluations (sharing).[2][3] The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as call-by-name.[citation 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值