The Daily Static
  The Daily Static
UF Archives
Register
UF Membership
Ad Free Site
Postcards
Community

Geekfinder
UFie Gear
Advertise on UF

Forum Rules
& FAQ


Username

Password


Create a New Account

 
 

Back to UserFriendly Strip Comments Index

recursive -> iterative by dennismv2004-12-21 02:24:43
  I think it would work by moddermonster 2004-12-21 07:10:53

in lots of cases. End recursion is trivial. True begin recursion is nothing more difficult. In the general case, something like bar: foo; bar(something); baz; return anything; it will heavily depend on the precise nature of something.

Basically all you have to do is to manually unroll the recursion and put this executing-the-same-code into appropriate loops. So first you iterate over all the foos (end recursion). Then you do the lowest-level special-case version of bar, then you do all the baz in reverse order, passing the return values on.

Now if you can predetermine the sequence of somethings, like in a factorial, you can easily unroll. If you have to calculate it in the foos, you might have to store it, i.e. build your own stack, queue or something. If you even need to calculate if (or when) bar is to be called at all, you're in trouble and cannot do it. And if foo or baz change some external state and look at it later on (thus building a hidden communication channel between the recursions), the program is crap anyway.

You can think about the recursion as the CPU iterating the same code over and over again, maintaining the local variables on its stack. When you try to code this as an iteration, you have to maintain the local variables yourself.

[ Reply ]
    You're forgetting something by Liava2004-12-21 11:55:08

 

[Todays Cartoon Discussion] [News Index]

Come get yer ARS (Account Registration System) Source Code here!
All images, characters, content and text are copyrighted and trademarks of J.D. Frazer except where other ownership applies. Don't do bad things, we have lawyers.
UserFriendly.Org and its operators are not liable for comments or content posted by its visitors, and will cheerfully assist the lawful authorities in hunting down script-kiddies, spammers and other net scum. And if you're really bad, we'll call your mom. (We're not kidding, we've done it before.)