Laziness

Chapter: Laziness

By now, you understand the term "purely functional". There are no side-effects in Haskell. Referential transparency is maintained: this means that whenever a function is called with the same arguments, it always returns the same result. Referential transparency makes it possible to reason mathematically about the behavior of functional programs.

Haskell is also lazy. This means that a function will not evaluate any of its arguments until they are needed. What about Scheme? Consider the following Scheme function:

(define ignore-second
  (lambda (x y)
    x))

Q. 1
What is the value of (ignore-second 3 4)?


Q. 2
Is the value of (ignore-second 3 (*anything*)) always 3?


Q. 3
If Scheme were lazy, would the value of (ignore-second 3 (*anything*)) always be 3?


An important benefit of lazy evaluation is that it enables us to deal with infinite data structures. For example, suppose we needed an infinite list of dollars. With lazy evaluation we could

(define billgates (cons "dollar" billgates))

So if we need a dollar, we can take the car of billgates. The cdr would still be an infinite list of dollars.

Q. 4
Why doesn't this work in Scheme?


Q. 5
Can you do the billgates thing in Haskell?


If we want to deal with infinite lists like this, we should either work in a lazy language like Haskell (which we do in the next chapter) or make changes to Scheme (as we do in later chapters) to make it behave in a lazy fashion.


rhyspj@gwu.edu