[Mention pattern guards Bryan O'Sullivan **20080818142828] { addfile ./examples/ch29/PatternGuard.hs hunk ./en/ch29-stm.xml 559 + + + + Pattern guards + + We sneaked one last language extension into our definition + of parseArgs. Pattern guards let us + write more concise guard expressions. They are enabled via + the PatternGuards language extension. + + A pattern guard has three components: a pattern, a + <- symbol, and an expression. The expression + is evaluated and matched against the pattern. If it matches, + any variables present in the pattern are bound. We can mix + pattern guards and normal Bool guard expressions + in a single guard by separating them with commas. + + &PatternGuard.hs:testme; + + In the above example, we return a value from the alist + xs if its associated key + x is present, provided the value is greater + than 3. The above definition is equivalent to the + following. + + &PatternGuard.hs:testme_noguards; + + Pattern guards let us collapse a collection + of guards and &case; expressions into a single guard, allowing + us to write more succinct and descriptive guards. hunk ./examples/ch29/PatternGuard.hs 1 +{-- snippet testme --} +{-# LANGUAGE PatternGuards #-} + +testme x xs | Just y <- lookup x xs, y > 3 = y + | otherwise = 0 +{-- /snippet testme --} + +{-- snippet testme_noguards --} +testme_noguards x xs = case lookup x xs of + Just y | y > 3 -> y + _ -> 0 +{-- /snippet testme_noguards --} }