[Haskell-cafe] Polymorphic (typeclass) values in a list?

Kalman Noel kalman.noel at bluebottle.com
Fri Oct 19 12:03:16 EDT 2007


TJ wrote:
> Why is it illegal to store values of differing types, but which
> instance the same class, into a list? e.g.
> 
> a = [ 1, 2.0 ] :: Num a => [a]

The problem is that Num a => [a] really means:

    forall a. Num a => [a]

That is, a list of type Num a => [a] could either be a list of Integers, or a
list of Doubles, or ..., but not a heterogeneous list.  Slightly varying the
type does not help, either:

    [forall a. Num a => a]

This would mean that each and every value in the list is itself polymorphic.
What we ultimately need could be written as

    [exists a. Num a => a]

i. e. for each value in the list there is a Num type to which the value belongs.
While there is no “exists” quantifier in Haskell types, you can use
existentially quantified types (existentials) for your purpose. Given the
following data type ExistsNumber

    data ExistsNumber = forall a. Num a => Number a
    instance Show Number where  -- So we can try this in ghci
        show (Number a) = show a

You may read the data declaration as: “(Number a) has type ExistsNumber if a
belongs to the type class Num, i. e. for all a in Num.”

Now you can “wrap” any value in the type class Num into an ExistsNumber value,
thus “forgetting” its concrete type. You can then construct a list of type
[ExistsNumber] easily:

    [ Number 1, Number (2::Int), Number (3::Double) ]

Kalman


More information about the Haskell-Cafe mailing list