[Haskell-beginners] Pattern Matching

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Sat Aug 2 22:37:10 EDT 2008


On 2008 Aug 2, at 22:09, Alex Watt wrote:

> same :: a -> a -> Bool
> same x x = True
> same _ _ = False
>
> Is there any way to do this in Haskell? The actual reason I'd like  
> to do this is something slightly more complicated. I want to match  
> against a list of elements, like so:

Not with pattern matching by itself; using a name in a pattern creates  
a new binding.

You can use guards:

 > same :: a -> a -> Bool
 > same x y | x == y = True
 > same _ _          = False

which simplifies to

 > same :: a -> a -> Bool
 > same x y = x == y

> foo [x,x,x] = ...


 > import Data.List
 > foo :: [a] -> Bool
 > foo x@(y:_:_:[]) = filter (== y) x

This becomes unwieldy for large lists; you would instead switch to a  
guard:

 > import Data.List
 > foo :: [a] -> Bool
 > foo x@(y:x') | length x == N = filter (== y) x' -- N is your  
expected list length
 > foo _ = False

or, possibly saving a few microseconds

 > import Data.List
 > foo :: [a] -> Bool
 > foo (y:x) | length x == N = filter (== y) x -- n is one less than  
your list length
 > foo _ = False

-- 
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20080802/6356454f/attachment-0001.htm


More information about the Beginners mailing list