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

Brent Yorgey byorgey at seas.upenn.edu
Sat Sep 4 12:29:39 EDT 2010

On Fri, Sep 03, 2010 at 10:51:59PM -0400, Alec Benzer wrote:
> 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. 

This is quite useful, and it comes up all the time.  I can't think of
a particular example off the top of my head, but I know I have written
lots of code with multiple type class constraints on the same type.

However, this isn't actually an advantage over Java, since Java
supports multiple interface inheritance.  You can just declare a new
interface that extends several other interfaces, and then use that new
interface instead of having to list multiple ones.

I don't think I'm qualified to comment on the precise differences
between interfaces and type classes, since I haven't thought about it
all that much.  Perhaps others can chime in with some differences.
There is this page on the Haskell wiki:



More information about the Beginners mailing list