[Mention a few limitations on pattern matching, and workarounds. Bryan O'Sullivan **20070722053230] { hunk ./en/ch03-funcs-types.xml 1227 + + Limits to pattern matching + + Every variable that appears within a pattern is a new + local variable that will be given a value if the pattern + matches, not a reference to some variable on + outside the pattern. Matching a pattern only + lets us do exact comparisons against constructors and simple + values. We can't use a pattern to match something like a + function. To see what we mean, take a look at the following + function. + + &BogusPattern.hs:isHead; + + A naive glance suggests that it's trying to check the + value of f to see if it's actually the + standard function head, but such an + interpretation would be quite wrong. Here's what is + really doing. + + Because the first pattern in the case + expression is just a variable, this pattern will + always match, no matter what the value of + f is, and the value of f + will be given to the local variable head + when the right hand side is evaluated. + + + A pattern that consists only of a variable will always + match, because it's not being compared against anything that + might cause the match to fail. We refer to patterns that + always match as irrefutable. + + + Finally, because the first pattern always matches, &GHC; + will always evaluate its right hand side and use that as the + result of the case expression. The second + pattern (the one with the wild card) will never actually be + reached. Because the two patterns will match the same values, + they are said to overlap. If &GHC; ever + complains to you about overlapping patterns, it's telling you + that one of your patterns is the same as another, and so will + never actually be matched. + + Another limitation of patterns is that a variable can only + appear once in a pattern. For example, you can't put a + variable in multiple places within a pattern to express the + notion this value and that should be + identical. + + The way around these restrictions of Haskell's patterns is + to use patterns in combination with a language facility called + guards, which we'll talk about + next. + + hunk ./en/ch03-funcs-types.xml 1311 - pattern matching, and guards lets us write code that's - clear and easy to understand. + pattern matching, and guards lets us write code that's clear and + easy to understand. hunk ./en/ch03-funcs-types.xml 1328 + Let's return to one of the limitations of patterns that we + mentioned in the previous section: the fact that we can't use a + pattern to check two variables within the pattern for equality. + We can express this quite easily using a guarded pattern. + + &Guard.hs:secondEqualsThird; + + Here, for good measure, we've illustrated guard syntax in a + case expression. }