0

I'm very new to Haskell, and I couldn't find the error in the following code:

arithmeticMean :: [Double] -> Double
arithmeticMean list = (sum list) / (length list)

I typed this into notepad, save it as "mean.hs", and tried to run it.

In GHCI, I typed :load mean and got the following error:

mean.hs:2:37:
Couldn't match expected type 'Double' with actual type 'Int'
In the second argument of '(/)', namely '(length list)'
In the expression: (sum list) / (length list)
Failed, modules loaded: none.

I apologize if I made a very trivial mistake, but I just don't see the problem. The function takes a list [Double], finds its sum, getting a double. Length takes any list and gives an int. I then divide a double by an int and return it. Why the error?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Pavel
  • 1,024
  • 1
  • 13
  • 20
  • 2
    the problem is that `length` will give an `Int` but `/` wants both sides to be of the same type - the simples solution is to use `fromIntegral` to *convert* the `Int`: `arithmeticMean xs = sum xs / (fromIntegral $ length xs)` – Random Dev Mar 14 '16 at 21:17
  • The numeric conversion rules in Haskell are quite simple: no implicit conversions (but numeric literals fit any numeric type). – chi Mar 14 '16 at 21:51

0 Answers0