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
(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.
Haskell takes a very different approach. It starts by performing type analysis with a type checker to understand your program at compile time. The type checker strictly prohibits type casting and does not allow type errors to be ignored.
What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).
in https://www.haskell.org/tutorial/goodies.html type [a] is defined as followed: [a] is the family of types consisting of, for every type a, the type of lists of a. Lists of integers (e.g. [1,2,3]), lists of characters (['a','b','c']), even lists of lists of integers, etc., are all members of this family.
Is there an example of a usage of cast which genuinely "changes" the type of a value from one type to another?
The simple answer is no. But, there may be a situation in which you do not know your type, since it is "hidden" by the quantifier "exists". Here's an example:
{-# LANGUAGE ExistentialQuantification #-}
import Data.Typeable
import Data.Maybe
data Foo = forall a . Typeable a => Foo a
main = print . catMaybes . map (\(Foo x) -> cast x :: Maybe Bool) $ xs
where
xs = [Foo True, Foo 'a', Foo "str", Foo False]
The output will be:
[True,False]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With