[Haskell-beginners] Average of numeric list
Elvio Rogelio Toccalino
elviotoccalino at gmail.com
Mon Apr 4 18:23:14 CEST 2011
2011/4/4 Daniel Fischer <daniel.is.fischer at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110404/3f856d8a/attachment.htm>
More information about the Beginners
mailing list