惰性评估和短路评估之间有何区别? [英] Any difference between Lazy evaluation and Short-circuit evaluation?

查看:164
本文介绍了惰性评估和短路评估之间有何区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自维基百科:

惰性评估 是:

Lazy evaluation is:

在编程语言理论中,懒惰求值或按需调用是 延迟对表达式进行评估的评估策略 直到需要它的值为止

In programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed

短路评估 是:

Short-circuit evaluation is:

短路评估,最小评估或麦卡锡评估 表示某些编程中某些布尔运算符的语义 仅执行或评估第二个参数的语言 如果第一个参数不足以确定 表达

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation denotes the semantics of some Boolean operators in some programming languages in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression

例如,当我有时,它们之间有什么区别?

So what's the difference between them for example when I have:

if(false && true && true) {
    //boo
} 

据我所知,编译器不会在false之后执行表达式,因为我有&&,所以整个表达式最终将是false. (对吗?)

As far as I know, compiler doesn't execute expressions after false because I have && so the whole expression will be false finally. (right?)

该行为是否称为惰性评估短路评估?

推荐答案

区别在于,在懒惰求值的情况下,仅在需要时才对表达式进行求值,而在短路求值的情况下,表达式求值会在您之后立即停止知道结果.这是一种正交的概念.

The difference is that in case of lazy evaluation an expression is evaluated only when it is needed, while in case of short-circuit evaluation expression evaluation stops right after you know the result. It's sort of orthogonal notions.

惰性评估可以应用于任何计算(短路方案通常仅用于布尔型). 它不会切断无用的计算,但会延迟整个计算,直到需要结果为止.

Lazy evaluation can be applied to any computation (short-circuit scheme usually is used only with bools). It doesn't cut-off useless computation, but delays the whole computation until its result is required.

variable = bigAndSlowFunc() or evenSlowerFnc()
if (carry out heavy computations)
  print "Here it is: ", variable
else
  print "As you wish :-)"

如果评估是惰性的,则仅当我们选择进入if的第一个(then)分支时,才会计算variable,否则不会计算.在评估阶段(当我们为print准备参数时),短路方案可用于确定是否需要调用evenSlowerFnc.

If evaluation is lazy, variable will be computed only if we choose to go into the first (then) branch of if, otherwise it won't. At the evaluation stage (when we prepare arguments for print) short-circuit scheme can be used to decide if we need to call evenSlowerFnc.

因此在您的示例中,这是短路评估,因为没有发生计算延迟.

So in your example, it's short-circuit evaluation since no delay of computation happen.

这篇关于惰性评估和短路评估之间有何区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆