What are Haskell guards?

Overview

Haskell guards are used to test the properties of an expression; it might look like an if-else statement from a beginner’s view, but they function very differently. Haskell guards can be simpler and easier to read than pattern matching.

Example

Let’s see an example

power :: Integer -> Integer
power x | x == 0 = 1 -- 1st guard
| x /= 0 = x * x -- 2nd guard
main = do
putStrLn "The square of 10 is:" -- Adding text for the output
print (power 10) -- printing to screen

Explanation

In the above coding example, we square the number:

In line 1: We instantiate our power function

In line 2: Our first guard, if x=0 let our `power’ be 1. (Just for illustration)

In line 3: Our second guard, multiplies the supplied number by itself (Squaring it)

In line 4: we initialize our main function

In line 5: we add a text for our output.

In line 6: We print our result

As stated earlier, guard can be seen as an if/else statement that is cleaner and easier to understand.

Output

The square of 10 is: 100

Free Resources