[Haskell-cafe] casting numerical types

Malcolm Wallace Malcolm.Wallace at cs.york.ac.uk
Sun Apr 2 05:53:02 EDT 2006


Matthias Fischmann <fis at wiwi.hu-berlin.de> writes:

>    avg :: (FractionalOrIntegral a) => [a] -> a
>    avg xs = sum (map fromFractionalOrIntegral xs) / (fromIntegral (length xs))

Your condition is probably too strong.  For one thing, there is no need
to convert every element of the list being summed, just its result.  Also,
does the final result need to be the same type as the elements?

    avg :: (Num a, Fractional b) => [a] -> b
    avg xs = fromRational (sum xs % toInteger (length xs))

Regards,
    Malcolm


More information about the Haskell-Cafe mailing list