[Haskell-cafe] existential types

Felipe Lessa felipe.lessa at gmail.com
Wed Feb 13 12:15:40 EST 2008


On Feb 13, 2008 2:41 PM, Jake McArthur <jake.mcarthur at gmail.com> wrote:
> Now we can have NumericLists like [1 :: Int, 5.7 :: Double, 4%5 ::
> Rational].

No, we can't =). Using

data NumericList = forall a . Num a => N [a]

*Main> let a = N [1::Int,2,3,4]
*Main> let b = N [1::Double,2,3,4]
*Main> let c = N [1::Int,2::Double]

<interactive>:1:18:
    Couldn't match expected type `Int' against inferred type `Double'
    In the expression: 2 :: Double
    In the first argument of `N', namely `[1 :: Int, 2 :: Double]'
    In the expression: N [1 :: Int, 2 :: Double]
*Main> let d = [a, b, N [1::Rational,2,3,4]]

The lists inside N will be homogeneous, but you can have a
(homogeneous) list of N's such that each N has a diferrent list type.
If you want a list of different types of numbers, you should do
something like

data Number = forall a. Num a => Number a
type NumberList = [Number]

x :: NumberList
x = [Number (1::Int), Number (2::Double), Number (3::Rational)]

or maybe

data NumberList2 = forall a . Num a => Cons a NumberList2
                 | Nil

x2 :: NumberList2
x2 = Cons (1::Int) $ Cons (2::Double) $ Cons (3::Rational) Nil


Cheers,

-- 
Felipe.


More information about the Haskell-Cafe mailing list