LYAH describes fromIntegral
as:
From its type signature we see that it takes an integral number and turns it into a more general number. That's useful when you want integral and floating point types to work together nicely.
I don't understand how this function works at all or why it is needed from playing around with the interpreter.
fromIntegral 4 + 3.2
7.2
4 + 3.2
7.2 -- seems to work just fine?!
fromIntegral 6
6
fromIntegral 6.2
-- raises an error
:t fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b -- does this mean it takes 1 arg or 2?
fromIntegral :: (Integral a, Num b) => a -> b
takes one arg. The =>
should be read as a logical implication with universal quantification:
for all types
a
andb
,if
a
is an instance ofIntegral
andb
is an instance ofNum
,then
fromIntegral
can take ana
and produce ab
.
This function converts a value of type a
(which is an Integral
type) to the b
type (which is an instance of the more general Num
class). E.g. you cannot add the integer 1
to the float 2
in Haskell without converting the former:
Prelude> (1 :: Int) + (2 :: Float)
<interactive>:10:15:
Couldn't match expected type `Int' with actual type `Float'
In the second argument of `(+)', namely `(2 :: Float)'
In the expression: (1 :: Int) + (2 :: Float)
In an equation for `it': it = (1 :: Int) + (2 :: Float)
Prelude> fromIntegral (1 :: Int) + (2 :: Float)
3.0
fromIntegral
will convert a integral value, such as Int
, to a more general value, a.k.a Num a
.
For example, (4 :: Int) + 3.2
will not type check, but fromIntegral (4 :: Int) + 3.2
will work just fine.
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