
On Monday 04 April 2011 17:15:20, Nadav Chernin wrote:
Hello,
I tried to write function mean - average of numeric list.
mean::(Fractional a)=>[a]->a mean a = (realToFrac (sum a)) / (realToFrac (length a))
But error occures:
Could not deduce (Real a) from the context (Fractional b) arising from a use of `realToFrac' To correct this function, i rewrite this function:
mean::(Real a, Fractional a)=>[a]->b mean a = (realToFrac (sum a)) / (realToFrac (length a))
Is there most simple way to write this function?
mean :: Fractional a => [a] -> a mean xs = sum xs / fromIntegral (length xs) Note however, that that's not a particularly efficient way to calculate the mean, since the compiler isn't smart enough to transform it into a loop traversing the list once (so allowing it to be garbage collected as it is consumed and the computation to run in constant space) and keeping the accumulators evaluated.
Thanks, Nadav