2011/4/4 Daniel Fischer <daniel.is.fischer@googlemail.com>
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?
For simple functions it is often revealing to define it in ghci and only then ask its type:
-- your version:
Prelude> let m2 as = (realToFrac $ sum as) / (realToFrac $ length as)
Prelude> :t m2
m2 :: (Real a, Fractional b) => [a] -> b
-- Daniel's version:
Prelude> let m1 as = sum as / (fromIntegral $ length as)
Prelude> :t m1
m1 :: (Fractional b) => [b] -> b
_______________________________________________
Beginners mailing list
Beginners@haskell.org
http://www.haskell.org/mailman/listinfo/beginners