1) How do you convert from one Int
type to a Num
type?
Similar questions have been asked before and the answer has been (as is on the Haskell wiki) is to use fromIntegral
. fromIntegral
returns a Num
type so I have to cast this to my desired format.
I need to take a Word16
and convert it to a Int64
so I am doing the following
let valueLength = (fromIntegral(tagLength) :: Int64)
where tagLength
has type Word16
Is this approach correct?
2) How do you handle type conversion safely?
Coming from a Java background where there is for Integers I believe Short
,Int
and Long
I can use a short
as an int
but not the other way around. In Haskell though if I write
256 :: Word8
in ghci
it returns 0.
Explicit Type Conversion In C // explicit type conversion double value = (double) number; Here, (double) - represents the data type to which number is to be converted. number - value that is to be converted to double type.
Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function. An example of typecasting is converting an integer to a string.
Data type conversion occurs automatically for different numeric types such as from floating-point database column values into integer C variables, and for character strings, such as from varying-length Ingres character fields into fixed-length C character string buffers.
Type conversion allows a compiler to convert one data type to another data type at the compile time of a program or code. 2. It can be used both compatible data type and incompatible data type. Type conversion is only used with compatible data types, and hence it does not require any casting operator.
I need to take a Word16 and convert it to a Int64 so I am doing the following:
let valueLength = (fromIntegral(tagLength) :: Int64)
Is this approach correct?
Let's ask GHC!
Prelude Data.Word Data.Int> :t fromIntegral :: Word16 -> Int64
fromIntegral :: Word16 -> Int64 :: Word16 -> Int64
Looks good.
How do you handle type conversion safely?
Haskell does not have type conversion. At all. All "conversions" must be done by writing a function that "converts" from one type to another.
If I write
256 :: Word8
inghci
it returns0
.
Number literals are polymorphic. For things with no decimal point, fromInteger
is used implicitly:
Prelude> :t 256
256 :: Num a => a
Prelude> :t fromInteger
fromInteger :: Num a => Integer -> a
Prelude> fromInteger (256 :: Integer) :: Word8
0
It might 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 file a feature request on GHC's bug tracker.
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