Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Haskell's Cast Operator

Tags:

haskell

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
like image 380
George Avatar asked May 15 '17 08:05

George


People also ask

What does -> mean in Haskell?

(->) 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.

Can you type cast in Haskell?

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 is the difference between int and Integer in Haskell?

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).

What is a in Haskell?

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.


1 Answers

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]
like image 104
freestyle Avatar answered Sep 28 '22 18:09

freestyle