[Haskell-beginners] Pattern Matching
rendel at daimi.au.dk
Sat Aug 2 22:18:57 EDT 2008
Alex Watt wrote:
> 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?
No, this is not possible. Each variable bound in a pattern has to be
different. Maybe guards are a good alternative:
same :: Eq a => a -> a -> Bool
same x y | x == y = True
same _ _ = False
Note that you have to add an Eq constraint.
> 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] = ...
Maybe you can employ the "all" function
all :: (a -> Bool) -> [a] -> Bool
in a guard, something like
foo (x:xs) | all (x ==) xs = ...
where you explicitly check that all list elements are equal to the first.
More information about the Beginners