6

I just tried to write a simple function to calculate the average of the input-Ints:

avg :: Int -> Int -> Int -> Float
avg x y z = (x+y+z)/3

When I exchange the signature to

avg :: Float -> Float -> Float -> Float

it works fine, but with the one above I get the following error message:

Couldn't match expected type 'Float' with actual type 'Int'.

Which possibilites do I have to use the first signature, which accepts Ints (only)?

user1000742
  • 183
  • 2
  • 10

2 Answers2

13

Use fromIntegral to convert the Ints to Floats:

avg :: Int -> Int -> Int -> Float
avg x y z = (fromIntegral x + fromIntegral y + fromIntegral z) / 3
hammar
  • 138,522
  • 17
  • 304
  • 385
dave4420
  • 46,404
  • 6
  • 118
  • 152
2

Shorter:

avg :: Int -> Int -> Int -> Float
avg x y z = (fromIntegral $ sum [x,y,z]) / 3.0

Or you generalize this for a list of Ints:

avg :: [Int] -> Float
avg xs = (fromIntegral $ sum xs) / (fromIntegral $ length xs)
Landei
  • 54,104
  • 13
  • 100
  • 195