Haskell/Solutions/Next steps
Introducing pattern matching
[edit | edit source]Exercises |
---|
We cheated a little when moving from the second version of pts to the third one: they do not do exactly the same thing. Can you spot what the difference is? |
The difference is what happens when the argument is smaller than 1
. In both the second and the third versions, they will be matched only on the final cases (by the catch-all patterns _
and x
, respectively). In the second version, the final case evaluates to 0
at once. In the third version, however, there is also the x <= 6
guard, which is evidently true when the argument is less than 1
; and thus the result will be 7 - x
. Thus, pts (-4)
for instance evaluates to 0
with the second version but to 11
with the third version.
N.B.: In a footnote to the text we claimed that for this example we wouldn't be too worried about what should happen if pts
was given nonsensical inputs; still, corner cases like this are the sort of issue that tends to trip us up when writing "real" code. In other words: it might make a difference in your program, so stay alert.
Here is a variation of the third version which is exactly equivalent to the second one:
pts :: Int -> Int
pts 1 = 10
pts 2 = 6
pts x
| x < 1 || x > 7 = 0
| otherwise = 7 - x