# [Haskell-cafe] casting numerical types

Matthias Fischmann fis at wiwi.hu-berlin.de
Sun Apr 2 06:39:32 EDT 2006

```On Sun, Apr 02, 2006 at 10:53:02AM +0100, Malcolm Wallace wrote:
> From: Malcolm Wallace <Malcolm.Wallace at cs.york.ac.uk>
> Date: Sun, 2 Apr 2006 10:53:02 +0100
> Subject: Re: [Haskell-cafe] casting numerical types
>
> 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))

you are right, your version looks better, and i managed to make ghc
eat these variants:

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

avg'' :: (RealFrac a, Fractional b) => a -> [a] -> b
avg'' epsilon xs = fromRational ((1 % toInteger (length xs)) * approxRational (sum xs) epsilon)

But the problem is that (%) requests integral types, and I do not want
to round my input.  Also, I have the same problem as above that
Integral types are not RealFrac, so these do not accept [Int] as
input.  When I try yours, however, I get:

Couldn't match the rigid variable `a' against `Integer'
`a' is bound by the type signature for `avg'
Expected type: a
Inferred type: Integer
In the application `toInteger (length xs)'
In the second argument of `(%)', namely `toInteger (length xs)'

So do I need 'toNum' now?

m.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature