Tidiest way to do recursion safely in R?

@alandipert This is very educational thankyou so much for taking the time to post. What's more is that the trampoline appears to work in R!

I fully expected it not to... since things like Recall and on.exit all consume stack. My tests proved me wrong though:

fib_tramp <- trampoline(function(num_seq = c(0,1), max_num = 1000){
  num_vals <- length(num_seq)
  if(num_vals == max_num){
    return(num_seq)
  }
  new_val = num_seq[num_vals] + num_seq[num_vals-1]
  recur(c(num_seq, new_val), max_num)
})

fib <- function(num_seq = c(0,1), max_num = 1000){
  num_vals <- length(num_seq)
  if(num_vals == max_num){
    return(num_seq)
  }
  new_val = num_seq[num_vals] + num_seq[num_vals-1]
  fib(c(num_seq, new_val), max_num)
}

fib(max_num = 10000)
# Error: C stack usage  7970164 is too close to the limit

fib_tramp(max_num = 100000)
#WORKS!

Also this seems like it could be packaged up nicely into a reusable tool!

edit: sorry @alandipert I originally attributed the trampoline to @nick, in my exictement

5 Likes