Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand :t for fromIntegral

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?
like image 610
user2415706 Avatar asked Apr 19 '14 09:04

user2415706


2 Answers

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 and b,

if a is an instance of Integral and b is an instance of Num,

then fromIntegral can take an a and produce a b.

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
like image 171
Fred Foo Avatar answered Oct 27 '22 02:10

Fred Foo


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.

like image 40
Lee Duhem Avatar answered Oct 27 '22 01:10

Lee Duhem