Jump to content

Haskell/Solutions/Pattern matching

From Wikibooks, open books for an open world

← Back to Pattern matching

Matching literal values

[edit | edit source]
Exercises
  1. Test the flawed h function above in GHCi, with arguments equal to and different from 1. Then, explain what goes wrong.
  2. In this section about pattern matching with literal values, we made no mention of the boolean values True and False, but we can do pattern matching with them as well, as demonstrated in the Next steps chapter. Can you guess why we omitted them? (Hint: is there anything distinctive about the way we write boolean values?)

1.

When used for pattern matching, a simple variable name like the k in

h k = True

binds k to the argument of h and, crucially, matches anything at all. Since we are not using the bound k variable in the right hand side of the equation, in this function the effect of this definition is the same of

h _ = True

Which is why GHC/GHCi complains about overlapping patterns, and why the second equation for h gets ignored. Also, the k = 1 definition made outside of the function has no influence on what happens - the k used in pattern matching has local scope (that of the h equation), and has nothing to do with that other k.

2.

Bool is not a literal value; rather, it is an algebraic datatype like the ones we first met in the previous chapter. In essence, its definition in Prelude amounts to simply:

data  Bool  =  False | True

False and True are parameterless constructors; and that is why their names start with a capital letter.

Syntax tricks

[edit | edit source]
Exercises
Implement scanr, as in the exercise in Lists III, but this time using an as-pattern.


myScanr step zero [] = [zero]
myScanr step zero (x:xs) = (step x y):ys
    where ys@(y:_) = myScanr step zero xs

You probably used head instead of an as-pattern in the first version of this exercise; here, on the other hand, we do not match the empty list in the pattern for ys. In this specific case, neither solution is actually unsafe, because the result of myScanr will never be an empty list. Nevertheless, pattern matching still is a better choice than head, as it makes it more obvious that we chose not to handle the empty list case.