Any difference between Lazy evaluation and Short-circuit evaluation?

前端 未结 1 1298
北恋
北恋 2021-02-05 09:18

From Wikipedia:

Lazy evaluation is:

In programming language theory, lazy evaluation or call-by-need is an evaluation strategy w

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 09:45

    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 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.

    0 讨论(0)
提交回复
热议问题