Skip to content
Prev 313648 / 398502 Next

recursion depth limitations

On 14 December 2012 13:46, Simon Urbanek <simon.urbanek at r-project.org> wrote:
Thank you Simon for your time and patient reply. I was thinking
calling another function over again is called indirect recursion.
NULL
[1] 99
I see what you mean. I was confused. My intention was having 100 calls
in the second one with f1 as well.
Maybe I can make the point with using another example via mutual
recursion, 'fibRping/pong' below.
But I was thinking 'fibRping' version would need less memory then the
plain recursion, which I now understand
that I was mistaken. Every call counts then. Even though I had an
impression that  calling the same
function more then once like fibRping/pong would not create additional
memory requirement ... (Probably the issue is noting to do with
Rs internals though..

Using Dirk's blog entry (http://dirk.eddelbuettel.com/blog/2011/09/08/) :
## R implementation of recursive Fibonacci sequence
fibR <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return (fibR(n - 1) + fibR(n - 2))
}


# Now Mutual recursion
fibRping  <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return (fibRpong(n - 1) + fibRpong(n - 2))
}
fibRpong  <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return (fibRping(n - 1) + fibRping(n - 2))
}

options(expressions=500000)
fibR(50000)> options(expressions=500000)
Error: C stack usage is too close to the limit
Error: C stack usage is too close to the limit