Pattern Matching on Literals

Learn about pattern matching on literal values.

We'll cover the following

Pattern matching on literals

Instead of using pattern variables, we can also write function equations using literal values as patterns. Here is an example:

isZero :: Int -> Bool
isZero 0 = True
isZero n = False


This function has two defining equations. The first one uses the numeric literal 0 as the pattern. We can read it as "if the argument to isZero is 0, the result is True". The second equation uses a pattern variable n, and says that the result to isZero should be False, for any value of n.

If a function has several defining equations, they will be applied from top to bottom for evaluating expressions involving the function’s application. However, an equation is only used if the argument to the function matches the pattern in the function equation. If several equations match, the first equation that matches is chosen.

The rules for matching are simple:

• Literal patterns match only the exact value they represent. That means 0 in the first equation of isZero matches only the Int value 0.
• Pattern variables match any value of the type they stand in for. So the variable n is the second equation if isZero matches any Int value.

For example, to evaluate the expression isZero 0, Haskell checks whether the first equation isZero 0 = True can be applied. This is the case because the argument 0 matches the literal pattern of the equation. So the result of isZero 0 is True. The second equation is ignored (although the pattern would match).

On the other hand, when evaluating isZero 5, the first equation can not be applied, as the argument 5 does not match the pattern 0. Thus, the second equation is tried, i.e. isZero n = False. As 5 matches the pattern variable n, this equation is used and the result is False.

If we load and run this function in ghci, we in fact see that it works as intended.

*IsZero> isZero 0
True
*IsZero> isZero 5
False


Here is a terminal running ghci where you can try out the isZero function:

Get hands-on with 1200+ tech skills courses.