Haskell Language Guards


Example

A function can be defined using guards, which can be thought of classifying behaviour according to input.

Take the following function definition:

absolute :: Int -> Int  -- definition restricted to Ints for simplicity
absolute n = if (n < 0) then (-n) else n

We can rearrange it using guards:

absolute :: Int -> Int
absolute n 
  | n < 0 = -n
  | otherwise = n

In this context otherwise is a meaningful alias for True, so it should always be the last guard.