Lecture 9-1
where
Syntax
Sometimes it is useful to bind names across a whole function:
remove_twos [] = []
remove_twos (x:xs)
| x == 2 = rest
| otherwise = x:rest
where rest = remove_twos xs
As the two expressions are in different guards then you can’t use a let
expression.
A general example is:
f x y = 1 + a + b
where a = 2 * x
b = y / 2
where
comes at the end of a function. Like let
it can bind any number of names
- These names are available throughout the function.
- They are not variables.
- You can do pattern matching in
where
clauses (and also inlet
expressions too).
An example of pattern matching:
initials first last = (x,y)
where (x:_) = first
(y:_) = last
let
v.s. where
let
is an expression.
> (let a = 1 in a) + (let a = 2 in a)
> 3
where
is syntax
- One
where
clause per function. - Particularly useful when used with guards.
remove_twos [] = []
remove_twos (x:xs)
| x == 2 = rest
| otherwise = x:rest
where rest = remove_twos xs
This means that where has to be joined to a function body and is always bound to that function body.
Exercises
-
func x = a + b + x where a = 2 * x + 1 b = a * a - x
-
countTwos [] = 0 countTwos (x:xs) | x == 2 = 1 + rest | otherwise = rest where rest = countTwos xs