[prev in list] [next in list] [prev in thread] [next in thread] 

List:       haskell
Subject:    Numeric conversions
From:       Andrew Rock <A.Rock () cit ! gu ! edu ! au>
Date:       1997-09-29 5:06:05
Message-ID: 199709290506.PAA21095 () kurango ! cit ! gu ! edu ! au
[Download RAW message or body]

Suppose you want to write a function like the following, hoping to be
able to get a function that can compute the mean of a list of
numbers, Integral or otherwise.

mean :: [a] -> Double
mean xs = sum xs / length xs

This is the sort of thing you might ask in an intoductory
programming subject.

You immediately have to deal with Haskell's type system.

Simple solutions can be found for each type a you might be
interested in:

> dmean :: [Double] -> Double
> dmean xs = sum xs / fromIntegral (length xs)

> imean :: [Int] -> Double
> imean xs = fromIntegral (sum xs) / fromIntegral (length xs)

The best way I've found to get the originally sought polymorphism
is this:

> mean :: Real a => [a] -> Double
> mean xs = real2frac (sum xs) / fromIntegral (length xs)

where

> real2frac :: (Real a, Fractional b) => a -> b
> real2frac = fromRational . toRational

The composition of fromRational and toRational seems to be the
only way to convert a Double or an Int to a Double.

There is a function in the prelude, fromRealFrac, with exactly
the same definition, but in the type signature, in place of Real
it has RealFrac. This renders it useless as a replacement for
my real2frac, as Int and Integer aren't instances of RealFrac.

Is there a better way to define a polymorphic mean using the 
current prelude definitions?

Why does the prelude have fromRealFrac instead of something
more generally useful like real2frac?

Thanks in advance,
Rock.
--
Andrew Rock -- arock@cit.gu.edu.au -- http://www.cit.gu.edu.au/~arock/
School of Computing and Information Technology
Faculty of Information and Communication Technology
Griffith University -- Nathan, Brisbane, Queensland 4111, Australia



[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic