[Haskell-beginners] Guards as extensions of patterns

Brent Yorgey byorgey at seas.upenn.edu
Wed Sep 29 23:45:08 EDT 2010


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


More information about the Beginners mailing list