Why is lazy evaluation useful?

后端 未结 22 1636
无人共我
无人共我 2020-11-29 17:04

I have long been wondering why lazy evaluation is useful. I have yet to have anyone explain to me in a way that makes sense; mostly it ends up boiling down to \"trust me\".<

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 17:50

    The most useful exploitation of lazy evaluation that I've used was a function that called a series of sub-functions in a particular order. If any one of these sub-functions failed (returned false), the calling function needed to immediately return. So I could have done it this way:

    bool Function(void) {
      if (!SubFunction1())
        return false;
      if (!SubFunction2())
        return false;
      if (!SubFunction3())
        return false;
    
    (etc)
    
      return true;
    }
    

    or, the more elegant solution:

    bool Function(void) {
      if (!SubFunction1() || !SubFunction2() || !SubFunction3() || (etc) )
        return false;
      return true;
    }
    

    Once you start using it, you'll see opportunities to use it more and more often.

提交回复
热议问题