
29 Sep
2010
29 Sep
'10
11:45 p.m.
On Wed, Sep 29, 2010 at 08:17:31PM -0700, Russ Abbott wrote:
I never realized that a guard can be used as an extension of a pattern. Is this recommended coding?
Absolutely. Pattern matching and guards can and should be mixed freely.
elem n xs asks whether n is an element of xs
elem :: (Eq a) => a -> [a] -> Bool
elem _ [] = False elem n (x:_) | n == x = True elem n (_:xs) = elem n xs
Yes, this works just fine, although personally I would actually write elem without a guard: elem _ [] = False elem n (x:xs) = n == x || elem n xs This is efficient (it stops as soon as it finds a match) since || is lazy. -Brent