[Haskell-cafe] cast to specific Typeclass
roma at ro-che.info
Fri May 15 20:52:40 UTC 2015
On 15/05/15 21:59, Teodor Vlasov wrote:
> Hello everyone,
> I'm trying to implement traversal over data structures and found
> Data.Typeable very useful for that. But it seems to be impossible to
> cast to specific typeclass, so that we can cast Typeable to something
> that is Show'able for example. It'd be usefull to have something like:
> data CanShow = forall a. CanShow a
> toConcrete :: (Typeable a) => a -> Maybe CanShow
> Implementing such datatypes for needed classes would allow to do some
> kind of class casting.
> Is it possible to implement this somehow?
> Is it a limitation of the implementation or a principal one?
Casting to a type works because all information is there, you only need
to convince the type system that it is fine to use it.
"Casting to a class" doesn't work because the type class implementation
(the method dictionary) is not contained in a value of that type.
Instead, compiler plugs it in during compile time where it is needed.
What you can do is try to cast a value to a number of known types, and
if one of those casts succeeds, get hold of the dictionary corresponding
to that monomorphic type.
What you *cannot* do is to find out at runtime which instances the
compiler knew about at compile time (let alone recover the dictionary);
that information is gone.
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 819 bytes
Desc: OpenPGP digital signature
More information about the Haskell-Cafe