Tuesday, August 28, 2012

Nested functions in R and Stata


#----------------- Starting in R -------------------------#

# Both R and Stata have built in limit of how many nested functions each package will allow.
a <- 0

recursive_call <- function() {
  a <<- a+1
  print(a)
  recursive_call()
}

recursive_call()
# R gives up at 2494 calls.

#-----------------Switching to Stata---------------------*

* This is an identical program (function) in Stata

global a=0

cap program drop recursive_call
program recursive_call

  global a=$a + 1
  di $a
  recursive_call

end


* Stata on the other hand throws in the towel at 63.  This looks bad but look at the response by Alan Riley!


* The Following Code is code from a email comment by Alan RileyStataCorp LP Vice President, Software Development

/* --------------------------- And In Mata------------------------------ */
set more off // don't pause every screen full of output
mata:

a = 0

function recursive_call() {
external a
a = a+1
printf("%f\n", a)
  recursive_call()
}

recursive_call()

end

/*

Alan: The above will error out at some point when it hits its recursion limit,
and Mata will print out a (long) traceback log intended to help in
debugging when a Mata function hits some system limit. Due to such deep
recursion, this traceback log will be long and so the output from
recursive_call() will scroll off the top of your screen. In any case,
after running the above, you can then re-enter Mata and see what the value
of "a" is:

mata:
a
end



*/

You should see 32766.




As an aside, you will notice that

* I imposed an upper limit of recursive calls at 10000, if left uncontrolled it will keep going till it gives an error. I am impressed with the speed and power of Mata!
recursive_call

No comments:

Post a Comment