[Haskell-cafe] How to implement the mean function
Ruohao Li
liruohao at gmail.com
Fri Jul 1 08:11:24 CEST 2011
For mean xs = sum xs / fromIntegral (length xs), I got the following:
test.hs:8:10:
Could not deduce (Fractional a)
from the context (Num a, Fractional b)
arising from a use of `/' at test.hs:8:10-42
Possible fix:
add (Fractional a) to the context of the type signature for `mean'
In the expression: sum xs / fromIntegral (length xs)
In the definition of `mean':
mean xs = sum xs / fromIntegral (length xs)
test.hs:8:10:
Couldn't match expected type `b' against inferred type `a'
`b' is a rigid type variable bound by
the type signature for `mean' at test.hs:7:27
`a' is a rigid type variable bound by
the type signature for `mean' at test.hs:7:13
In the expression: sum xs / fromIntegral (length xs)
In the definition of `mean':
mean xs = sum xs / fromIntegral (length xs)
And the div way will do integer division, which is not what I want.
On Fri, Jul 1, 2011 at 2:07 PM, Nathan Howell <nathan.d.howell at gmail.com>wrote:
> (/) operates on a Fractional instance... but length returns an Int, which
> is not a Fractional.
>
> You can convert the Int to a Fractional instance:
> mean xs = sum xs / fromIntegral (length xs)
>
> or try an integer division:
> mean xs = sum xs `div` length xs
>
> -n
>
> On Thu, Jun 30, 2011 at 10:55 PM, Ruohao Li <liruohao at gmail.com> wrote:
>
>> Hi guys,
>>
>> I just started learning some Haskell. I want to implement a mean function
>> to compute the mean of a list. The signature of the function is:
>> mean :: (Num a, Fractional b) => [a] -> b
>> But when I implement this simple function, the compiler keep whining at me
>> on type errors. I know this is wrong:
>> mean xs = sum xs / length xs
>> But how to get it right? Thanks.
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110701/b90ce8f6/attachment.htm>
More information about the Haskell-Cafe
mailing list