COMPARING THE LAZY EVALUATION TECHNIQUES

Both techniques demonstrated in the preceding sections have their various good and bad sides. The next few paragraphs describe some of the considerations you should make when applying one or both of these techniques to a problem.

Usability

If you have existing functions that take values as parameters, it is an easy change to replace these either with function types or with a Lazy<T> encapsulation. In both cases you must also change the call sites — that is, the places where the parameters are being evaluated — but those are simple changes and the compiler will help you because your code breaks once you have changed the types of the parameters.

For new code, you may find that depending on your style of programming as well as the extent to which you have adopted pure functions, it might come very naturally to pass functions in a lot more places than you used to do. If your code is already a network of functions, as suggested in the introduction, it is often an easy afterthought to add laziness through function passing into the mix — or you might even find yourself using it without noticing. However similar the Lazy<T> approach may be to Haskell, in C# it means using different types, so this will never happen by chance.

Another reason why Lazy<T> requires some additional consideration is that it can only represent operations without parameters. As the samples have shown, it is not hard to incorporate this necessity into your code, but again, ...

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.