[Haskell-cafe] casting numerical types

Matthias Fischmann fis at wiwi.hu-berlin.de
Sat Apr 1 13:11:05 EST 2006

hi all,

this should be a quick one (for now I would be happy with a "that's
impossible", just want to make sure I don't miss anything).  I want to
compute the average from a list of arbitrary numerical element type.
I wanted to do this:

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

but it doesn't compile.  All I could get to work is this:

    avg :: (Fractional a) => [a] -> a
    avg xs = sum xs / (fromIntegral (length xs))

    avgI :: (Integral a) => [a] -> Float
    avgI = avg . map fromIntegral

The two function names for the same thing are tolerable, but not very
elegant.  Is there another option?

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060401/9dda58d0/attachment.bin

More information about the Haskell-Cafe mailing list