[Haskell-cafe] Typeable and Dynamic
oleg at okmij.org
oleg at okmij.org
Tue Nov 4 00:16:02 EST 2008
minh thu asked a tricky question, about writing
> extract :: Typeable a => TypeRep -> Dynamic -> a
The question here is what determines the type 'a'. One answer is that
'a' is determined from the context, e.g.,
(extract tr dyn) + 1.0
fixes 'a' to be an Int. In that case, extract is equivalent to `read'
(indeed, String is a primitive sort of Dynamic). We do not need any
argument TypeRep though as we obtain 'a' from the context. fromDynamic
is sufficient there.
One can also construe the question to be asking about writing an `inverse' of
typeOf. Whereas,
typeOf :: Typeable a => a -> TypeRep
can give the TypeRep for any (Typeable) type,
undefinedOf :: Typeable a => TypeRep -> a
could give (an undefined) value for a given TypeRep.
Now, the _type_ 'a' is determined by the _value_ of TypeRep: seemingly we
need dependent types. To write function of exactly that signature, we
need Template Haskell. Oftentimes, we can get away with a weaker
function:
> data Dyn = forall a. Typeable a => Dyn a
> reflect :: TypeRep -> Dyn
to be used to implement dynApply, dynFst, dynSnd, dynHead and other operations
on Dynamics. Perhaps the following message may help then
http://www.haskell.org/pipermail/haskell-cafe/2007-December/036820.html
More information about the Haskell-Cafe
mailing list