O'Reilly logo

Real World Haskell by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Introducing Local Variables

Within the body of a function, we can introduce new local variables whenever we need them, using a let expression. Here is a simple function that determines whether we should lend some money to a customer. We meet a money reserve of at least 100, and we return our new balance after subtracting the amount we have loaned:

-- file: ch03/Lending.hs
lend amount balance = let reserve    = 100
                          newBalance = balance - amount
                      in if balance < reserve
                         then Nothing
                         else Just newBalance

The keywords to look out for here are let, which starts a block of variable declarations, and in, which ends it. Each line introduces a new variable. The name is on the left of the =, and the expression to which it is bound is on the right.

Special notes

Let us reemphasize our wording: a name in a let block is bound to an expression, not to a value. Because Haskell is a lazy language, the expression associated with a name won’t actually be evaluated until it’s needed. In the previous example, we could not compute the value of newBalance if we did not meet our reserve.

When we define a variable in a let block, we refer to it as a let-bound variable. This simply means what it says: we have bound the variable in a let block.

Also, our use of whitespace here is important. We’ll talk in more detail about the layout rules later in this chapter in The Offside Rule and Whitespace in an Expression.

We can use the names of a variable in a let block both within the block of declarations and in the expression ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required