[Haskell-beginners] Average of numeric list
Nadav Chernin
nadavchernin at gmail.com
Tue Apr 5 10:38:37 CEST 2011
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
On Mon, Apr 4, 2011 at 7:23 PM, Elvio Rogelio Toccalino <
elviotoccalino at gmail.com> wrote:
>
>
> 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
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110405/fd0830da/attachment-0001.htm>
More information about the Beginners
mailing list