[Haskell-beginners] Type classes vs Java interfaces

Peter Hall peter.hall at memorphic.com
Fri Feb 1 02:43:16 CET 2013


The Java type system is a lot less rich. You can take an object and call
methods on it, knowing only that it implements an interface. In Haskell,
you can do so much more. You don't even need an implementation, you can
rely on the type of the binding instead:

extremes :: Bounded b => Bool -> b
extremes lower = if lower then minBound else maxBound
-- e.g.
extremes True :: Int -- -9223372036854775808
data Foo = A | B | C | D deriving (Bounded, Show)
extremes False :: Foo -- D

Or (with a few language extensions), you can have the typeclass take
multiple arguments. In Java, you can't do anything like this:

class Convert a b where
   convert :: a -> b

instance Show a => Convert a String where
   convert = show

instance Convert Foo String where
   convert A = "A"
   convert B = "B"
   convert C = "C"
   convert D = "D"


Peter


On 31 January 2013 23:36, Mateusz Kowalczyk <fuuzetsu at fuuzetsu.co.uk> wrote:

> Greetings,
>
> I often wonder how one would explain type classes to someone coming from
> an environment such as Java. Whenever I think about type classes, I seem
> to think of them as Java interfaces. Bah, even the bottom of [1] states
> > Haskell classes are roughly similar to a Java interface. Like an
> interface declaration, a Haskell class declaration defines a protocol
> for using an object rather than defining an object itself.
>
> Is there more to this `roughly similar' statement? Syntax is an obvious
> difference but beyond that, I can't think of anything I can do with a
> Haskell type class that I wouldn't be able to do with similar amount of
> effort with a Java interface, except for the fact that the interface
> would look absolutely disgusting syntax wise.
>
> Any insight appreciated.
>
>
> [1] - http://www.haskell.org/tutorial/classes.html
>
> _______________________________________________
> 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/20130201/528c16b2/attachment.htm>


More information about the Beginners mailing list