[Haskell-beginners] Re: question about styles of recursion

7stud bbxx789_05ss at yahoo.com
Thu Mar 26 16:43:24 EDT 2009


Michael Mossey <mpm <at> alumni.caltech.edu> writes:

> 
> In RWH, in the exercises at the end of the book,

There are no 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'. 

Ok. That sounds like you are working on the exercises for chapter 3
on p.69, specifically exercise 3.  The length function was introduced 
before the sum function, which I see you are using in your 
function definition.  See p. 15. The length function was also 
mentioned in exercise 1, and the instructions for exercise 3 mention
using the length of the list.

> 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
> 

Use variables that are defined? 

Prelude Data.List> :load ehask.hs 
[1 of 1] Compiling Main             ( ehask.hs, interpreted )

ehask.hs:3:44: Not in scope: `n'
Failed, modules loaded: none.










More information about the Beginners mailing list