Casting dynamic values

George Russell ger@tzi.de
Tue, 27 Nov 2001 23:59:19 +0100


It would occasionally be nice to have a function
   cast :: (Typeable a,Typeable b) => a -> Maybe b
which returns Just a if a and b have the same type, and Nothing otherwise.
This may seem rather a curious need, but it arises with existential
types; if you have
   data A = forall a . (context) => A a
(context including Typeable a) then this allows you to
getB :: (Typeable b) => A -> Maybe b
getB (A a) = cast a

and so extract a value from A, if you can guess its type.

Clearly we can implement
   cast = fromDynamic . toDyn

My question is: is this the most efficient way of doing it, or is there
a better way?