Here are my answers to the exercises in the Haskell Wikibook: Pattern Matching chapter:
Test the flawed
h
function above in GHCi, with arguments equal to and different from 1. Then, explain what goes wrong.The following code:
k = 1 h :: Int -> Bool h k = True h _ = Falsewon't compile because the
k
that's defined to equal 1 is different from thek
in the pattern. The two patterns forh
overlap, they both match everything, one is anonymous and one is bound tok
.In this section about pattern matching with literal values, we made no mention of the boolean values
True
andFalse
, 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?)The literal values True and False begin with capital letters, and so could be confused with Types or Constructors.
Implement
scanr
, as in the exercise in Lists III, but this time using an as-pattern.myScanr :: (a -> b -> b) -> b -> [a] -> [b] myScanr f n l = foldr g [n] l where g x list@(y:ys) = (f x y) : list