Super-dee-duper D features

renoX renosky at free.fr
Tue Feb 13 22:47:50 PST 2007


Lutger a écrit :
> renoX wrote:
>>> Recursion just has a nerdy aura around it. It probably doesn't help that
>>> most programmers are learned to think iteratively too.
>> And it doesn't help recursion that when you transform a recursive
>> function to a tail recursive function so that it's not too slow, the
>> result is ugly!
> 
> How is that so? Could you give an example? I'm not very familiar with
> recursive programming actually...

A "natural" factorial:
fact(n):
if (n <= 1)
	return 1;
else
	return n * fact(n - 1);

Here fact is not tail recursive because the last operation is * not f.
So if you want an efficient implementation you have to rewrite it as:

fact(n) = fact2(1,n);
fact2(acc,n):
if (n == 1)
	return acc
else
	return fact2(acc*n, n-1);

Bleach. That's fugly.

renoX



More information about the Digitalmars-d mailing list