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 < .. duh..
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re (tilly) 2: catching infinite loops
by tilly (Archbishop) on Apr 20, 2001 at 16:04 UTC |