[Haskell-beginners] question about styles of recursion

Michael Mossey mpm at alumni.caltech.edu
Thu Mar 26 12:19:18 EDT 2009


In RWH, in the exercises at the end of the book, I was told to write a 
function that averages the integer values in a list. I wanted to do this 
using on the tools we had been presented, which did not include 
'length'. So I thought of writing a recursive function in which each 
case passes an accumulator of the "sum so far" as well as a count of 
node "up to the point", and the base case does the actual division. I 
was wondering if there is a better way of doing it (using the just ideas 
up to chapter 3, so no length, no higher order functions, no foldr/foldl 
or map).

myAvg' :: Int -> [Int] -> [ Double ] -> Double
myAvg' sum count []     = sum / fromIntegral count
myAvg' sum count (x:xs) = myAvg' (x + sum) (n + 1) xs

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

Thanks,
Mike


More information about the Beginners mailing list