[Haskell-cafe] Existential Types (I guess)
Neil Brown
nccb2 at kent.ac.uk
Fri Jan 22 06:36:59 EST 2010
Ozgur Akgun wrote:
> data NumHolder = forall a. Num a => NumHolder a
>
> instance Show NumHolder where
> show (NumHolder n) = show n
>
> liftNum :: (Num a) => (a -> a) -> NumHolder -> NumHolder
> liftNum f (NumHolder c) = NumHolder (f c)
The problem here is that you declare that liftNum will work for any
single type a, decided (effectively) by the caller of the function. But
if the caller chooses Int for a, and your NumHolder has a Float inside
it, that isn't going to work. You need to take a function that will
work for any Num type a:
liftNum :: (forall a. Num a => a -> a) -> NumHolder -> NumHolder
liftNum f (NumHolder c) = NumHolder (f c)
This uses Rank2Types, but that's necessary for what you want. By moving
the forall from being implicit at the start of the signature to inside
the brackets, you declare that this is a function that works for all
types a (that are a member of type-class Num). This should compile and
work as you wanted.
Neil.
More information about the Haskell-Cafe
mailing list