Understanding Haskell's Cast Operator

Viewed 848

Assume that we have imported Data.Typeable which contains cast :: (Typeable a, Typeable b) -> a -> Maybe b.

Consider that

> cast 'n' :: Maybe Char
Just 'n'

yet

> cast 7 :: Maybe Char
Nothing

I understand the above, but it seems to be a trivial example. It doesn't reveal why someone would need to use the cast operator (as far as I can see).

Question: Is there an example of a usage of cast which genuinely "changes" the type of a value from one type to another? The closest example I can think of (which doesn't actually work in GHCi) would be changing the type of 7 from Integer to Double:

> cast 7 :: Maybe Double
Just '7' -- this doesn't work, as 7 is typed as a Integer above; instead GHCi returns Nothing
3 Answers
Related