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: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