Why is lazy evaluation useful?

后端 未结 22 1605
无人共我
无人共我 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:51

    Here are two more points which I do not believe have been brought up in the discussion yet.

    1. Laziness is a synchronization mechanism in a concurrent environment. It is a lightweight and easy way to create a reference to some computation, and share its results among many threads. If multiple threads attempt to access an unevaluated value, only one of them will execute it, and the others will block accordingly, receiving the value once it becomes available.

    2. Laziness is fundamental to amortizing data structures in a pure setting. This is described by Okasaki in Purely Functional Data Structures in detail, but the basic idea is that lazy evaluation is a controlled form of mutation critical to allowing us implement certain types of data structures efficiently. While we often speak of laziness forcing us to wear the purity hairshirt, the other way applies too: they are a pair of synergistic language features.

提交回复
热议问题