# [Haskell-beginners] Average of numeric list

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
>
> 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