5 Strictness and laziness

 

This chapter covers

  • Strict vs. non-strict functions
  • Implementing a lazy list data type
  • Memoizing streams to avoid recomputation
  • Inspecting streams to visualize and test
  • Separating program description from evaluation
  • Infinite streams and corecursion

Kotlin, like most modern programming languages, uses strict evaluation by default. That is, it allows only functions whose parameters must be entirely evaluated before they may be called. In all our examples so far, we have focused on this evaluation strategy, also know as eager or greedy evaluation. In fact, this is what we have been using while deriving data types such as List, Option, and Either. We will look at a more formal definition of strictness later, but what does strict evaluation imply in the real world?

Strictly evaluated expressions are evaluated at the moment they are bound to a variable. This includes when they are passed to functions as parameters. This strategy is acceptable if we merely assign a simple value, but what if our expression performs an expensive or complex computation to determine its value? And, taking this a step further, what if this expensive computation is to be used in expressing all elements of a list data type, where we might only need the first few elements?

5.1 Strict and non-strict functions

5.2 An extended example: Lazy lists

5.2.1 Memoizing streams and avoiding recomputation

5.2.2 Helper functions for inspecting streams

5.3 Separating program description from evaluation

5.4 Producing infinite data streams through corecursive functions

5.5 Conclusion

Summary