[Haskell-beginners] (Implicit) equality testing using multiple function definitions
Arlen Cuss
celtic at sairyx.org
Tue Jul 19 03:05:06 CEST 2011
19/07/2011 10:44 AM, Tom Murphy kirjutas:
> Hi list!
> When I define an algebraic datatype without an instance for Eq,
> I'm obviously unable to use the (==) function on it. I can
> pattern-match with a series of function definitions (f [] = False; f x
> = True) on the expression, though. Why is that?
> I understand that in the second case I'm not literally using the
> (==) function, but it seems like there would be instances where you'd
> intentionally not want to be able to test for equality, and
> pattern-matching with multiple function definitions circumvents that.
My take on this (may not be canonical, or even right!) is that pattern
matching is matching on the shape of the object. E.g. with the data type:
> data Foo a = Bar a | Quux a
.. then it's not possible to stop someone matching on a Foo a to
determine if it was constructed with Bar or Quux. If you couldn't know
that, it'd be impossible to do .. well, anything at all with it.
But Foo a isn't an Eq instance, even if a happens to be, because we
haven't defined the rules by which that happens. Deriving Eq is an easy
way to do that, but it simply may not make sense to do so.
Pattern matching is a different beast to testing for equality. Though I
have few good examples, you can't match on 'x' for an arbitrary 'x' at
run-time: the shape has to be determined at compile-time. That means you
can only use (nested) constructors, so e.g. you can't match the contents
of a Data.Map.
Cheers,
Arlen
More information about the Beginners
mailing list