Skip to main content

Guards

Guards are a way of testing whether some property of a value (or several of them) are true or false.

  • very similar to if statement.
  • guards are a lot more readable when you have several conditions
  • they play really nicely with patterns.
info

pattern matching in function definitions is syntactic sugar for case expressions

simple guards

max' :: forall a.(Ord a) => a -> a -> a
max' a b
| a > b = a
| otherwise = b
info

Note that there's no = right after the function name and its parameters, before the first guard.

guards with pattern matching

A guard is a boolean-valued expression that must be satisfied in addition to the constraints imposed by the patterns.

gcdV2 :: Int -> Int -> Int
gcdV2 n 0 = n
gcdV2 0 n = n
gcdV2 n m | n > m = gcdV2 (n - m) m
| otherwise = gcdV2 n (m - n)