Reputation: 127
how do you define the mean using type [Float]
, without using recursion? also giving the answer to two decimal places. I'm new to Haskell so any help would be really really appreciated. I.e. mean :: [Float] -> Float
.
For mean xs = sum xs / length xs
, I got the following:
No instance for (Fractional Int)
arising from a use of `/' at test.hs:8:10-27
Possible fix: add an instance declaration for (Fractional Int)
In the expression: sum xs / length xs
In the definition of `mean': mean xs = sum xs / length xs
Upvotes: 1
Views: 164
Reputation: 23955
If you only want two decimal points, without rounding, you could use div
rather than /
(you'll have to move the decimal point in the result...):
meanish xs = div (sum xs * 100) (length xs)
Upvotes: 0
Reputation:
Let's look at /
:
(/) :: Fractional a => a -> a -> a
As you see the result of /
is of the same type as the operands.
Now let's look at length
:
length :: [a] -> Int
Oops! You're passing an integer to /
. Since (disregarding 0) the set of integers is not closed under division, /
is not overloaded for integers.
Therefore, you first have to convert the second operand to floating-point number:
mean :: [Float] -> Float
mean xs = sum xs / fromIntegral (length xs)
As for giving the answer to two decimal places, I'd leave that to the code responsible for presenting the result to the user. That's not the responsibility of mean
.
Upvotes: 6