[Haskell-cafe] programming style...and type classes...

David Menendez dave at zednenem.com
Sun Nov 6 03:06:19 UTC 2016

On Sat, Nov 5, 2016 at 11:45 AM, Olaf Klinke <olf at aatal-apotheke.de> wrote:

> While we have stated in this thread what typeclasses should _not_ be used
> for, we probably do not have carved out yet what `proper' use is. Please
> help me here.

It may be helpful to recall the original purpose of classes, which was to
allow controlled, ad-hoc overloading. Otherwise, we’d be stuck using
specialized functions for every type, passing around explicit equality
tests, or being stuck with the equivalent of deriving(Eq) on every type.

Now that we have qualified types, we can write algorithms which are generic
over class members. This, I would say, is the sign that a class is useful.
If you can’t usefully write code which is generic over a class, then you
don’t gain much from using the class. (You do gain not having to come up
with new names, though, and that’s not nothing.)

Some people claim that you shouldn’t define a class unless you can describe
some sort of algebraic laws for it, but I think that’s too strong. For one
thing, it would mean we lose equality and numeric operations for Float,
which is one of the things classes were invented for in the first place.

Instead, define a class if (1) you have a set of operations that can be
applied at multiple types but aren’t polymorphic, (2) you can give a formal
or informal description of the operations which are enough to reasonably
distinguish a good instance from a bad one, and (3) using a class makes
your code easier to understand.

Dave Menendez <dave at zednenem.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20161105/7e74c3d9/attachment.html>

More information about the Haskell-Cafe mailing list