Skip to content

Instantly share code, notes, and snippets.

@hgiasac
Created January 4, 2019 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hgiasac/508654591ad35378ec986af2d948ffb2 to your computer and use it in GitHub Desktop.
Save hgiasac/508654591ad35378ec986af2d948ffb2 to your computer and use it in GitHub Desktop.
-- no equality
cast :: (Typeable a, Typeable b) => a -> Maybe b
cast x = r
where
r = if typeOf x == typeOf (fromJust r)
then Just $ unsafeCoerce x
else Nothing
-- with equality
eqT :: forall a b. (Typeable a, Typeable b) => Maybe (a :~: b)
eqT = if typeRep (Proxy :: Proxy a) == typeRep (Proxy :: Proxy b)
then Just $ unsafeCoerce Refl
else Nothing
cast :: forall a b. (Typeable a, Typeable b) => a -> Maybe b
cast x
| Just Refl <- ta `eqT` tb = Just x
| otherwise = Nothing
where
ta = typeRep :: TypeRep a
tb = typeRep :: TypeRep b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment