[Haskell-beginners] Average of numeric list

Daniel Fischer daniel.is.fischer at googlemail.com
Tue Apr 5 11:14:31 CEST 2011


On Tuesday 05 April 2011 10:38:37, Nadav Chernin wrote:
> Why only  "length as" we must to cast? Why "sum as", that have type
> Integer can be used in (/).
> 
> :t (/)
> 
> (/) :: (Fractional a) => a -> a -> a

No, sum as has the type of as's elements,

sum :: Num a => [a] -> a

So the use of (/) refines the constraint from (Num a) to (Fractional a).
if you want it to work on Integers too,
you'd get

mean :: (Real a, Fractional b) => [a] -> b
mean xs = realToFrac (sum xs) / (fromIntegral $ length xs)



More information about the Beginners mailing list