[Haskell-beginners] Help with types
Daniel Fischer
daniel.is.fischer at web.de
Thu Apr 23 09:35:12 EDT 2009
Am Donnerstag 23 April 2009 14:57:58 schrieb Daniel Carrera:
> Hi,
>
> I want to make a simple "average" function:
>
> average xs = (sum xs)/(length xs)
>
> When I try that on ghci I get the following error:
>
> No instance for (Fractional Int)
> arising from a use of `/' at <interactive>:1:17-36
> Possible fix: add an instance declaration for (Fractional Int)
> In the expression: (sum xs) / (length xs)
> In the definition of `average': average xs = (sum xs) / (length xs)
>
> Ok, so 'sum' is of type (Num a => [a] -> a), length is of type ([a] ->
> Int) and (/) is of type (Fractional a => a -> a -> a). Can someone
> explain how I can "add an instance declaration" to my function so as to
> make all these types compatible?
Don't. (you wouldn't add the instance declaration to the function, anyway, but to your
module)
Try explicitly converting the length to the appropriate type:
average xs = sum xs / fromIntegral (length xs)
will yield a working (albeit inefficient)
average :: Fractional a => [a] -> a
>
> Thanks,
> Daniel.
More information about the Beginners
mailing list