Newsgroups: comp.lang.scheme
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!oitnews.harvard.edu!purdue!lerc.nasa.gov!magnus.acs.ohio-state.edu!math.ohio-state.edu!howland.reston.ans.net!swrinde!tank.news.pipex.net!pipex!news.mathworks.com!uunet!in2.uu.net!allegra!alice!ark
From: ark@research.att.com (Andrew Koenig)
Subject: Re: Tail recursivity
Message-ID: <DFyG3D.3yF@research.att.com>
Organization: AT&T Bell Laboratories, Murray Hill NJ
References: <44uee7$dnc@academ00.mty.itesm.mx>
Date: Thu, 5 Oct 1995 02:54:49 GMT
Lines: 30

In article <44uee7$dnc@academ00.mty.itesm.mx> al522331@openlab85.mty.itesm.mx (RAFAEL ALGARA TORRE) writes:

> I am writing a very simple function to calculate the number of
> ocurrences of an element in a list, done in normal recursion it
> becomes very easy, though, I'm forced to write it with tail
> recursion. Given that it is a multiple recursion function, how do I
> accumulate the partial results?

By defining an auxiliary function that takes the accumulator as an extra
argument.

I don't speak Scheme well enough to be able to show you how to do it in
Scheme, but here it is in C:

	int count_aux(int *array, int n, int x, int accum)
	{
		if (n == 0)
			return accum;
		return count_aux(array+1, n-1, x, accum+(*array==x));
	}

	int count(int *array, int n, int x)
	{
		return count_aux(array, n, x, 0);
	}

See Abelson and Sussman for more details.
-- 
				--Andrew Koenig
				  ark@research.att.com
