🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Where Clauses

A where clause is a block of bindings attached to the end of one definition. The definition above it can use those names in its own calculation.

A definition can use its where binding

The definition works out price times quantity, minus discount. The where block below gives discount the value 5.

total price quantity = price * quantity - discount
  where discount = 5

main :: IO ()
main = print (total 20 3)

A where block can hold several bindings

The definition adds area and perimeter. The where block works out both names from the width and height inputs.

boxTotal width height = area + perimeter
  where area = width * height
        perimeter = 2 * (width + height)

main :: IO ()
main = print (boxTotal 3 4)

Each where block belongs to its own definition

Both functions use a name called factor in their where blocks. The first factor is 2 and the second is 3, and each function sees only its own.

doublePrice price = price * factor
  where factor = 2

triplePrice price = price * factor
  where factor = 3

main :: IO ()
main = print [doublePrice 10, triplePrice 10]

Example

orderTotal count priceEach = subtotal - discount + delivery
  where subtotal = count * priceEach
        discount = 8
        delivery = 7

main :: IO ()
main = print (orderTotal 3 20)

Key points

  • Where clause: a set of bindings written at the end of a definition, after the word where.
  • Placement: the where block is indented under the definition it belongs to.
  • Use above: the definition above the where block can use every name bound in it.
  • Scope: a name bound in a where block belongs to that one definition only.
  • Several bindings: a where block can hold several bindings, one under the other.

In this example, the where block works out a subtotal of 3 times 20, which is 60. The definition then takes off the discount of 8 and adds the delivery charge of 7, giving 59.

Note

two definitions can each have a where binding with the same name and different values, because each block is separate.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Where can a name bound in a where block be used?