in reply to catching infinite loops

It depends on how you write things. For example, rather than writing a function iteratively (i.e., using the loop structure), write it recursively. Catching loops is then a matter of making sure you're not trying to calculate something you've previously tried to calculate - unless there's some random stuff in your function (making it a not-function :) if you've visited the same place twice, you're in a loop.

The only thing to catch then is infinite diversions - such as, "Sum of all numbers to N" could be written:

sum nums_to_n { my $n = shift; if ($n==0) return 0; else return $n + nums_to_n ($n-1); }

This obviously loops indefinitely for $n < 0, which is not good. Usually, the answer is to make sure that your base case always occurs - that is, you can guarantee that there are certain values you can always calculate, and that you only accept values which rely, ultimately, on those values you can calculate.

updated: changed a < into &lt; .. duh..

Replies are listed 'Best First'.
Re (tilly) 2: catching infinite loops
by tilly (Archbishop) on Apr 20, 2001 at 16:04 UTC
    Random note.

    In Perl deep recursion leaks a lot of memory and is a lot slower than you would ever suspect. These two facts are connected.

    I have not tested with the current version, but also note that tail recursion with goto &my_sub does not get the performance you would hope for with a long argument list (there is adjusting of the stack), and appears to have a memory leak somewhere.

    Don't let this scare you off of recursion as a technique, but do be aware that you don't just want to blindly turn iterative loops into recursion.