Type conversion

1) How do you convert from one type Int to type Num ?

Similar questions were asked before, and the answer was (like on the Haskell wiki) - use fromIntegral . fromIntegral returns a Num type, so I have to specify it in the desired format.

I need to take Word16 and convert it to Int64 , so I do the following

 let valueLength = (fromIntegral(tagLength) :: Int64) 

where tagLength is of type Word16

Is this approach right?

2) How do you handle type conversion safely?

Based on the Java background, where there is for integers, I consider Short , Int and Long I can use Short as Int , but not vice versa. In Haskell though, if I write

 256 :: Word8 

in ghci it returns 0.

+6
source share
1 answer

I need to take Word16 and convert it to Int64, so I do the following:

 let valueLength = (fromIntegral(tagLength) :: Int64) 

Is this approach right?

Let me ask the GHC!

 Prelude Data.Word Data.Int> :t fromIntegral :: Word16 -> Int64 fromIntegral :: Word16 -> Int64 :: Word16 -> Int64 

Looks nice.

How do you handle type conversion safely?

Haskell has no type conversion. At all. All "conversions" must be performed by writing a function that "converts" from one type to another.

If I write 256 :: Word8 in ghci , it returns 0 .

Numeric literals are polymorphic. For things without a decimal point, fromInteger used implicitly:

 Prelude> :t 256 256 :: Num a => a Prelude> :t fromInteger fromInteger :: Num a => Integer -> a Prelude> fromInteger (256 :: Integer) :: Word8 0 

It would be nice if there was a warning or something for numeric literals with a monomorphic type that were out of range for that type; perhaps you should submit a request for a function to track GHC errors.

+20
source

All Articles