[Haskell] Re: reflection/metadata in Haskell?
stefan at cs.uu.nl
Fri Sep 23 03:55:00 EDT 2005
> mkT :: (Typeable a, Typeable b) => (b -> b) -> a -> a
> mkT f = case cast f of
> Just g -> g
> Nothing -> id
> From the definition of cast and the examples given earlier it looks
> like cast needs to be told what the target type (a here) is in
> order to
> know what its trying to cast to - hence the example was "(cast
> 'a')::Maybe Char" - which makes sense. So I dont quite understand the
> usage of cast presented here inside mkT. How does the case proceed
> without knowing what its trying to cast f to?
Well, it can proceed because all type information it really needs is
The explicit signature reveals that mkT has type
(b -> b) -> a -> a
(for any a and b that are instances of Typeable).
Using this information we derive that f in
mkT f = ...
is a function of type b -> b, right?
Then the right-hand side: that one should give us a function of type
a -> a. Just skip the first part of the case statement for a while
and proceed to its body:
mkT f = case ... of
Just g -> g
Since, g has to have type a -> a and Just has type t -> Maybe t for
all t, it follows that Just g has type Maybe (a -> a). Therefore the
case statement should perform pattern matching on a value of type
Maybe (a -> a). So, from
mkT f = case cast f of
Just g -> g
it can be inferred that cast f has type Maybe (a -> a) and, hence,
that cast should try to case f to a function of type a -> a.
More information about the Haskell