[Haskell-cafe] Library API design: functional objects VS type classes

Edsko de Vries edskodevries at gmail.com
Tue Mar 5 14:50:57 CET 2013


What is the advance of using type classes? A function of the form

  f :: Show a => ...

really has an implicit argument

  f :: Show__Dict a -> ...

that the compiler infers for us. So, the advantage of type classes is one
of convenience: we don't have to pass dictionaries around, or even figure
out which dictionaries we need; the compiler does that for us. But if we
have a type class of the form

  class Foo a where
    mkFoo :: IO FooToken
    otherFun1 :: FooToken -> ...
    otherFun2 :: FooToken -> ...

then this advantage is mostly lost; we still need to pass around an
explicit FooToken object. In a case like this, I don't see the advantage of
using a type class over using a data type

  data Foo = Foo { otherFun1 :: ... , otherFun2 :: ... }
  mkFoo :: .. -> Foo

There are exceptions; for instance, if you want to encode 'inheritance' in
some way then type classes might still be useful; for instance, see the
Gtk2Hs library, which uses this extensively.

Edsko
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20130305/96a61e1a/attachment.htm>


More information about the Haskell-Cafe mailing list