Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: RE: Recursive program calls and the return list


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: Recursive program calls and the return list
Date   Tue, 21 Oct 2008 18:45:16 +0100

Notwithstanding good advice from others, it seems to me that a much
simpler way to proceed is to use globals. 

cap prog drop recr
prog recr, rclass
    args count stopit
    if `count' == `stopit' {
      global something`count' = -99
    }
    else {
      global something`count' = uniform()
      local k = `count' +1
      recr `k' `stopit'
    }
end
// Start count at 0, run 5 times
recr 0 5
mac list

Nick 
[email protected] 

Mike Lacy

I've been experimenting with implementing recursive calls to a Stata 
program, and in particular, getting the program to store something in 
the return list at each call, so that at the end of program, the 
return list would contain r(something1) , r(something2), ..., 
r(somethingNumberOfCalls).  I have experienced various difficulties 
in not clobbering the return list.  Here's a simple example to 
demonstrate one of the problems I have had:

///  A "do nothing" recursion example; recur calls itself "stopit"
times,
// and tries to return something each time in the locals something0,
// something1, something2, ..,  but only "something0" shows up in the 
return list
cap prog drop recr
prog recr, rclass
    args count stopit
    if `count' == `stopit' {
      return local something`count' = -99
    }
    else {
      return local something`count' = uniform()
      local k = `count' +1
      recr `k' `stopit'
    }
end
// Start count at 0, run 5 times
recr 0 5
ret list

macros:
         r(something0) : ".2769154107663781"

How could this be changed so as to accumulate something in the return 
list at each recursive call?


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index