in reply to Tail-recursion in perl?!

All these solutions contain the same essential steps, but the first one (no recursion) has no unnecessary extras.

The only way I can imagine doing better on long-term performance would be for a persistent program to maintain previously requested results in a hash, which can be looked up instead of calculated; but that seems way overkill.

One world, one people

Replies are listed 'Best First'.
Re^2: Tail-recursion in perl?!
by Tanktalus (Canon) on Jul 10, 2005 at 16:43 UTC

    We all can disagree what constitutes overkill. But someone has gone a step further, and generalised persistant programs' ability to remember previously requested results. Check out Memoize ("trade space for time"). It inserts itself into the call-stream somewhat magically, and detects function calls that are identical, and returns the previously-computed value for the same input.

    Of course, this only makes sense when the same input always results in the same output, as it would here. This can really speed up recursive results to the point where, for some functions, the recursively-computed value is faster than the iterative. And, of course, Memoize can help simplify non-recursive functions as well. It does require a bit of caution to ensure that there are no side effects possible on a function, though.

    [time elapses...] Oddly, Memoize has a bunch of add-ons that I just saw when I checked it out on CPAN (to ensure I got the link correct above) which allows this to work even for non-persistant programs. That merits some more thought. Man, do I love perl. This would be incredibly programmer-intensive in basically any other language. But in perl, someone did it already, and I can just use it. That's too cool.