[Haskell-beginners] Defining an instance: Syntax that works exactly sometimes
Kim-Ee Yeoh
ky3 at atamo.com
Thu Jan 22 16:57:59 UTC 2015
Jeffrey,
You didn't explain what you're trying to accomplish, and therefore folks
can only address the symptoms.
Here's what I'm seeing:
Suppose you have:
data A = A | B | C | D | E
You'd like a function that
given A returns E,
given B, returns D
given C, returns er, C
given D, returns B,
given E, returns A.
So you're hoping to write a Rev type class with singleton member
rev :: Rev a => a -> a
that would do the trick.
Thing is, you can already write a very generic
rev :: (Enum a, Bounded a) => a -> a
that would do the job.
Why is that sweet?
Because Enum + Bounded are auto-derivable for huge swathes of data types.
So you write the rev function (not type class instance!) once, and it'll
work for lots of your structures.
The best type class is often no type class. Especially when the compiler
isn't smart enough to read your mind. But I'm sure it's flattered you
thought so highly of it ;)
-- Kim-Ee
On Thu, Jan 22, 2015 at 7:23 AM, 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/20150122/c6e9d0d8/attachment.html>
More information about the Beginners
mailing list