[Haskell-beginners] Heterogeneous Lists

Ertugrul Söylemez es at ertes.de
Tue May 28 19:08:10 CEST 2013


harry <voldermort at hotmail.com> wrote:

> > (2) A type class cannot be used as a type.
>
> Yes, (2) is what I don't understand.

The question can be generalized:  What is the difference between
Haskell's type classes and OOP interfaces?  The main difference is that
type class instances are type-bound, while interfaces are value-bound.
That's why you can't encode the Monoid pattern as a type class, but not
as an interface.

You /can/ think of type classes as types, but not the way you do it for
OOP interfaces or base classes.  A type class is a separate type that
encodes values of the type it is bound to:

    data Monoid a =
        Monoid {
          mempty  :: a,
          mappend :: a -> a -> a
        }

If you would store a list of monoids [Monoid X], you would store a list
of identity/addition laws for the same type X, not a list of values of
type X.  This is probably not what you want.


> I recently ran into this with a GUI application, where I needed to
> process a list of widgets that were members of the same typeclass, but
> I had to wrap them all because they were different types.

Your misconception is likely that you need to /store/ widgets, because
you think in terms of memory.  What you really need is /definitions/ of
widgets, which can very well have different types.  Then you can combine
them using the usual monadic or applicative interface.


> So so rephrase my question, why can't type classes be used as a type?
> Is this an implementation issues, or is there a semantic problem with
> this? Creating an existential type and packing all the values seems
> like busy work which shouldn't be necessary, or at least something
> that the compiler should be doing for me.

It is necessary.  Haskell's type system is simply not the same as C#'s
type system.  As pointed out a number of times we don't have subtyping.
Subtyping lets you treat different types like they were the same.
Haskell simply doesn't follow this philosophy and gives us enough type
system power to encode proper abstractions instead of the catch-all
"everything is an object" approach.

This is a benefit, but it takes some time to get used to it, and usually
you see the value only /after/ that time.


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130528/f29e42c3/attachment.pgp>


More information about the Beginners mailing list