Laziness in Lists

Let's study lazy evaluation in the context of lists and see how this allows us to define and work with infinite lists.

In the previous chapter, we studied lazy evaluation as a general concept in Haskell. We will now see how this concept carries over to lists, allowing for greater efficiency and expressiveness.

Lazy evaluation in lists

Let’s recall the general principle of lazy evaluation in Haskell.

Function arguments are only evaluated if this is necessary to determine whether the pattern of an equation matches.

This also means that in a chain of nested function calls, like head (map f xs), the outermost function application (head) will be evaluated first, and the inner function map will only be evaluated when necessary to evaluate head.

When working with lists as function arguments, this has a special benefit. Usually, it is not necessary to evaluate lists completely to see if they match a pattern.

Most list functions work with the patterns [] and (x:xs). To check whether an input list matches these patterns, we do not need to evaluate the whole list. Instead, we only need to evaluate the list as much as is necessary to check whether the list is empty or not. So, we only need to try and compute the first element of the list.

Get hands-on with 1200+ tech skills courses.