Pattern Matching on Literals
Explore how to use literal values as patterns in Haskell function definitions. Understand the matching rules for literals versus pattern variables, including the use of wildcards, and see examples with numeric and Boolean types. This lesson helps you write functions that handle special cases elegantly using literal pattern matching.
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 ...