WHAT’S GOOD ABOUT BEING LAZY?

There are two main intentions in lazy evaluation. First, it can make program execution more efficient. In imperative programming, execution order is always important. In complex algorithms it is often difficult to decide under which circumstances something should or shouldn’t be done, and the techniques used to “get it right” typically rely on a very specific execution order. Lazy evaluation offers an alternative approach, which comes with its own practical considerations and the need for a different style, but also the promise of optimal efficiency gains and vastly simplified algorithms in many situations. In languages that default to non-strict, lazy evaluation, programmers need ways to trigger strict evaluation occasionally. The important thing is having a choice.

Second, in traditional functional languages execution order typically doesn’t play a big role at all. Functions have dependencies, which result in requirements for the order of evaluation. But should it be the programmer’s task to figure this out? It shouldn’t, and as this book continuously describes, the science of pure functions makes it possible to describe algorithms as a network of functions, with the “connections” defined by the dependencies. In this world, being lazy is an important part of being efficient, to avoid the side effect of executing expensive computations in places where the need isn’t really clear yet.

Finally, of course, being lazy is always a virtue for a programmer ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.