[R] R recursion depth and stack size

Pascal A. Niklaus Pascal.Niklaus at unibas.ch
Tue Nov 25 16:10:56 CET 2003


Hi all,

I am playing around with latin squares, and wrote a recursive function 
that searches for valid combinations.
Apart from the fact that there are very many, I run into troubles 
beginning with size 10x10 because the recursion depth becomes too large 
(max of 10x9-1=89 in this case).

Why is this a problem? Isn't there enough space allocated to the stack? 
Can this be increased? The memory demand shouldn't be terrible, with 
only minimal local variables (only set and the function params r,c,t - s 
is local to a block called only once when a solution is found). Even if 
variables aren't stored efficiently, a recursion depth of 100 shouldn't 
consume more than a couple of kilobytes.

Is this a fundamental misunderstanding of the way R works?

Pascal

BTW: Is there a way to pass variables "by reference" in function calls?

------

The function stripped-down to the essential looks like this:

latin.square <- function(t = 4)
{
    latinCheck <- function(r,c,t)
    {
        set <- setdiff(LETTERS[1:t],c(m[r,],m[,c]));
        for(i in set)
        {
            m[r,c] <<- i;
            if(c<t)
            {
                latinCheck(r,c+1,t);
            }
            else
            {
                if(r<t)
                {
                    latinCheck(r+1,1,t);
                }
                else # found a solution
                {
                    s <- paste(m[1,],collapse="",sep="");;
                    for(i in 2:t)
                    {
                        s <- paste(c(s,"-",m[i,]),collapse="",sep="");
                    }
                    cat(s,"\n");
                }
            }
        }
        m[r,c] <<- NA;
    }

    latinSolutions <<- character(0);
    fullset <<- LETTERS[1:t];

    m <<- matrix(nrow=t,ncol=t);
    m[1,] <<- LETTERS[1:t];
    latinCheck(2,1,t)
}

l




More information about the R-help mailing list