[Haskell-beginners] Real world example of Typeclasses > Interfaces

Alec Benzer alecbenzer at gmail.com
Fri Sep 3 22:51:59 EDT 2010


Very new to Haskell, but I was just mulling this over; when I first learned
about typeclasses, I saw the apparent benefit of being able to assert that a
parameter to a function belongs to two typeclasses instead of just one. Ie,
in Java, for example, you can ensure that a parameter to a function belongs
to a particular interface by doing something like:

int doSomething(Comparable c) { ... }

But there's no real way of ensuring an argument implements two interfaces,
whereas in Haskell you can make sure that an argument belongs to two (or
however many) typeclasses.

doSomething :: (Ord a, Eq a, OtherTypeClass a) => a -> Int
...

But as I thought about this, I couldn't seem to think of a practical case
where this would be useful. The basic typeclasses in Haskell seem to follow
a hierarchy. Ie, anything that belongs to Ord belongs to Eq, anything that
belongs to Enum belongs to Ord, anything that belongs to Num belongs to
Enum. I suppose there may be certain cases involving Functors where there
would be a point to specifying multiple typeclasses (eg, an Int would not
work with (Functor a, Ord a)), but I guess I'm still somewhat skeptical
about how often such a check would be necessary in practical applications.

So I guess I'm just wondering if someone could give me an example of a
practical case of the typeclass system allowing you to do a check like this
that would not have been possible with interfaces. Or is there another
benefit to typeclasses over interfaces that I've missed?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100903/1974cf49/attachment.html


More information about the Beginners mailing list