[Haskell-beginners] Pattern Matching

Chris Eidhof chris at eidhof.nl
Sun Aug 3 05:01:39 EDT 2008

Hey Alex,

On 3 aug 2008, at 04:09, Alex Watt wrote:

> Hi there,
> The best way I can explain what I'd like to do is show an example,  
> so here goes:
> 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:
> foo [x,x,x] = ...

If you want to check whether all elements of the list are the same,  
you'd need a function of type [a] -> Bool. There is no such function  
in the standard libraries (search for this type using Hoogle [1]).  
Fortunately, Hoogle will point us to all, which only needs a function  
from (a -> Bool) that is checked on every member of the list. One way  
we could solve this problem is to see whether all elements are equal  
to the first element. This is trivially expressed:

allEqual :: Eq a => [a] -> Bool
allEqual xs = all (== head xs) xs

This also works for the empty list: because of lazy evaluation the  
expression "head xs" is only computed when actually needed.


[1]: http://www.haskell.org/hoogle/?q=[a]+-%3E+Bool

More information about the Beginners mailing list