Re: How can I STOP a cursed recursion?
- Posted by Juergen Luethje <j.lue at gmx.de> Jun 19, 2006
- 572 views
Dan Moyer wrote: > Ricardo M. Forno wrote: > >> Hi Dan. >> In any case, to stop a recursive procedure you must test its ending *before* >> calling it. If not, it will recurse forever, until it eats all available >> storage. >> Typical example (code not tested) >> >> function factorial (atom x) >> if x = 0 then >> return 1 >> end if >> return factorial(x - 1) * x >> end function > > Hi Ricardo, > > Here's like what I did, except that I have a number of other tests inside > the procedure which can re-call the procedue with different values to > act on, (those tests & consequences DID work), but the STOPPING didn't work: > > integer STOP > STOP = 0 > procedure Help() > if STOP then > return > end if > print(1,"help!") > Help() > if getTime() = 6am then > STOP = 1 -- How can I let the procedure *stop itself*!? > end if > > end procedure > Help() > > After I get some sleep, > I'll try Juergen's suggestion, which I think is to only call the procedure > from within itself when some "*not*-finished" condition is met, rather than > trying to use "return" to STOP it when the finished condition *is* met. No, that's not the point. Previously I wrote ...
integer Count, NumTimes procedure Help() puts(1,"Help!\n") Count += 1 if Count < NumTimes then Help() end if end procedure Count = 0 NumTimes = 3 Help()
... but we can use as well:
integer Count, NumTimes procedure Help() puts(1,"Help!\n") Count += 1 if Count >= NumTimes then return end if Help() end procedure Count = 0 NumTimes = 3 Help()
Inspired by Ricardo's post, I see now that the same can be done without any local (or global) variable:
procedure Help(integer times) if times > 0 then puts(1,"Help!\n") Help(times-1) end if end procedure Help(3)
Or ...
procedure Help(integer times) if times <= 0 then return end if puts(1,"Help!\n") Help(times-1) end procedure Help(3)
Here is an Introduction to Recursion <http://personal.vsnl.com/erwin/recintro.htm>. Regards, Juergen -- Please excuse my flawed English. My native language is Euphoria.