Reputation: 23135
Is there nice way to write the following "x is of type t" parts? (I suspect I should be using Data.Type.Equality but I'm not sure exactly how)
f :: a -> Int
g :: b -> Int
h :: Typeable t => t -> Maybe Int
h x = case x of
(x is of type a) -> Just (f x)
(x is of type b) -> Just (g x)
_ -> Nothing
Upvotes: 1
Views: 70
Reputation: 44603
This is a job for the "type safe cast" bits of Data.Typeable
. cast :: (Typeable a, Typeable b) => a -> Maybe b
pulls the runtime type information out of the Typeable
dictionaries for a
and b
and compares them; if a
and b
are the same type then it returns Just
its argument, otherwise it fails.
So, with cast
and Maybe
's Alternative
instance in hand, we have:
h x = f <$> cast x
<|> g <$> cast x
As far as I know, there's no way to avoid the repetitious calls to cast
, since they occur at different types.
Upvotes: 3