Re: How to write a nonrecursive program ?
- From: Ertugrul Söylemez <es@xxxxxxxx>
- Date: Sun, 23 Nov 2008 02:27:00 +0100
richard@xxxxxxxxxxxxxxx (Richard Tobin) wrote:
In article <20081121220433.050f52f1@xxxxxxxx>,
Ertugrul Söylemez <es@xxxxxxxx> wrote:
In most cases, you can easily get around this by just adding an
accumulation parameter:
int factorial(int x, int b) {
if (x == 0) return b;
return factorial(x - 1, b*x);
}
I'd be interested to see how you algorithmically turn the original
recursive factorial into that, as opposed to coming up with a
completely different, but tail-recursive, method.
Note that the tail-recursive version performs the multiplications in a
different order, so an algorithmic transformation needs to know about
the associativity of multiplication.
In functional terms, this is actually the difference between left folds
and right folds. The recursive version is a right fold. Correct would
be to write a left fold in the first place, because the right fold is,
as you said, a completely different algorithm.
Greets,
Ertugrul.
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
.
- References:
- Re: How to write a nonrecursive program ?
- From: Ertugrul Söylemez
- Re: How to write a nonrecursive program ?
- From: Richard Tobin
- Re: How to write a nonrecursive program ?
- From: Ertugrul Söylemez
- Re: How to write a nonrecursive program ?
- From: Richard Tobin
- Re: How to write a nonrecursive program ?
- Prev by Date: Re: [OT] Size of a process
- Next by Date: Re: How to write a nonrecursive program ?
- Previous by thread: Re: How to write a nonrecursive program ?
- Next by thread: obfuscated code
- Index(es):
Relevant Pages
|