[Haskell-beginners] question about styles of recursion

Brent Yorgey byorgey at seas.upenn.edu
Thu Mar 26 14:09:00 EDT 2009


On Thu, Mar 26, 2009 at 09:19:18AM -0700, Michael Mossey wrote:
>
> myAvg' :: Int -> [Int] -> [ Double ] -> Double
> myAvg' sum count []     = sum / fromIntegral count
> myAvg' sum count (x:xs) = myAvg' (x + sum) (n + 1) xs

The definition of myAvg' looks fine, but I think you have the wrong
type signature there.

>
> myAvg :: [Double] -> Double
> myAvg xs = myAvg' 0 0 xs

You could also do it without accumulating parameters, like this:

myAvg xs = sum / count
  where (sum, count) = sumCount xs

sumCount :: [Double] -> (Double, Int)
sumCount [] = (0,0)
sumCount (x:xs) = (s+x, c+1)
  where (s,c) = sumCount xs


-Brent


More information about the Beginners mailing list