chapter five

5 Strictness and laziness

 

This chapter covers:

  • Understanding the difference between strict and non-strict functions
  • Implementing a lazy list data type
  • Memoizing streams to avoid recomputation
  • Inspecting streams for the purpose of visualizing and testing
  • Separating program description from evaluation
  • Consuming infinite streams and grasping corecursion

Kotlin, like most modern programming languages uses strict evaluation by default. That is, it allows only functions whose parameters must be evaluated completely 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 really imply in the real world?

Strictly evaluated expressions are evaluated at the moment that they are bound to a variable. This includes when they are passed to a function as parameter. This strategy is acceptable if we are merely assigning a simple value, but what if our expression performs some 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 of 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  Summary