In this chapter we introduce lazy evaluation, the mechanism used to evaluate expressions in Haskell. We start by reviewing the notion of evaluation, then consider evaluation strategies and their properties, discuss infinite structures and modular programming, and conclude with a special form of function application that can improve the space performance of programs.
Introduction
As we have seen throughout this book, the basic method of computation in Haskell is the application of functions to arguments. For example, suppose that we define a function that increments an integer:
inc :: Int -> Int
inc n = n + 1
Then the expression inc (2*3) can be evaluated as follows:
inc (2*3)
= {applying * }
inc 6
= {applying inc }
6 + 1
= {applying + }
7
Alternatively, the same final result can also be obtained by performing the first two function applications in the opposite order:
inc (2*3)
= {applying inc }
(2*3) + 1
= {applying * }
6 + 1
= {applying + }
7
The fact that changing the order in which functions are applied does not affect the final result is not specific to simple examples such as the above, but is an important general property of function application in Haskell. More formally, in Haskell any two different ways of evaluating the same expression will always produce the same final value, provided that they both terminate. We will return to the issue of termination later on in this chapter.
We also note that the above property does not hold for most imperative programming languages, in which the basic method of computation is changing stored values. For example, consider the imperative expressionn + (n = 1)that adds the current value of the variable n to the result of changing its value to one. Assuming that n initially has the value zero, this expression can be evaluated by first performing the left-hand side of the addition
or alternatively, by first performing the right-hand side:
n + (n = 1)
= {applying n }
0 + (n = 1)
= {applying = }
0 + 1
= {applying + }
1
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.