[Haskell-beginners] Defining an instance: Syntax that works exactly sometimes

Ryan Trinkle ryan.trinkle at gmail.com
Thu Jan 22 00:31:51 UTC 2015


In both cases, it's not actually creating a typeclass instance.  However,
because (<=) from Ord is declared in GHC.Classes, you're able to create a
new (but completely unrelated) function named (<=).  The fully qualified
names for these would be GHC.Classes.<= and YourModule.<=, so they don't
clash (but if you tried to use <= without qualifying it, you'd get an
ambiguous reference error).

In the case of Rev, you get an error, though, because both the class method
and the standalone function are declared in YourModule, which is illegal
(multiple declarations of the same name).

So, long story short, go with the "instance" syntax.

On Wed, Jan 21, 2015 at 7:23 PM, Jeffrey Brown <jeffbrown.the at gmail.com>
wrote:

> Dear Haskellers,
>
> The following compiles. (Rev stands for Reversible, and Dirn for
> Direction.)
>
>     class Rev a where
>         rev :: a -> a
>
>     data Dirn = Succ | Pred
>         deriving (Eq, Show, Ord)
>
>     -- implement Ord
>     (<=) Succ Pred = False
>     (<=) _ _ = True
>
>     -- implement Rev
>     instance Rev Dirn where
>         rev Succ = Pred
>         rev Pred = Succ
>
> But if I try to define the Rev instance the same way the Ord instance is
> being defined, it does not compile:
>
>     class Rev a where
>         rev :: a -> a
>
>     data Dirn = Succ | Pred
>         deriving (Eq, Show, Ord, Rev)
>
>     -- implement Ord, because Dirn is used as a key in a Map
>     (<=) Succ Pred = False
>     (<=) _ _ = True
>
>     -- implement Rev
>     rev Succ = Pred
>     rev Pred = Succ
>
> What's going on?
>
> Many thanks,
> Jeff
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150121/79f9bd8d/attachment.html>


More information about the Beginners mailing list