[Haskell-cafe] existential types
Jake McArthur
jake.mcarthur at gmail.com
Wed Feb 13 11:41:03 EST 2008
Let's try a different example. Let's start with a list designed to
hold numbers:
data NumericList a = Num a => [a]
Normally this would be fine. We can hold things like [1, 2, 3, 4, 5]
and [1.7, 5.3, 2.0, 99.1]. But what if we wanted to be able to hold
numbers with _different types_ in the list? That is, we won't know
anything about them except that they are instances of Num. That is
where existential types come in:
data NumericList = forall a . Num a => [a]
Now we can have NumericLists like [1 :: Int, 5.7 :: Double, 4%5 ::
Rational]. The only useful thing you can do with the values, in this
case, is apply functions of the Num type class, but there are times
when this is useful. (There are actually ways to cast these values
back to their original types elsewhere, but I'll ignore that because
it is far out of the scope of your question).
Does this help?
- Jake
More information about the Haskell-Cafe
mailing list