Search code examples
rfunctionrecursionfunctional-programmingoperator-keyword

Why does "Sum()" succeed where "+" fails in recursive R function?


I am experimenting with the functional programming paradigm in R. I have defined a function that sums a sequence of integers from n to m. When I use sum() the function returns the expected result:

sumRange <- function(n, m) {
    if (n <= m) { 
        return(sum(n, sumRange((n + 1), m)))
    }
}

sumRange(1, 10)
# [1] 55

However, when I use the + operator the function returns numeric(0):

sumRange <- function(n, m) {
    if (n <= m) {
        return(n + sumRange((n + 1), m))
    }
}

sumRange(1, 10)
# numeric(0)

Why does the operator + not work in this recursive function? Is there a way to rewrite the function so that it does?


Solution

  • The issue is that you never specify an else condition, hence at the end of the recursion it appears that R is returning NULL when the if condition fails. Returning 0 as the else condition fixes your problem:

    sumRange <- function(n, m) return(ifelse (n <= m, (n +  sumRange((n+1), m)), 0))
    sumRange(1, 10)
    [1] 55
    

    Note that this is essentially defining a base case for your recursion. A base case, when hit, ends the recursion and causes the calls on the stack to be unwound.

    To see the issue with the way you phrased your code, try writing out your function explicitly:

    sumRange <- function(n, m) {
        if (n <= m) {
            return(n + sumRange((n+1), m))
        }
        // but what gets returned if n > m ?
        // this is undefined behavior
    }
    

    I'm not an R guru, but my understanding is that R was written in C, and C might allow a recursion like this with no else condition. But the behavior is not well defined and you should not be relying on it.

    Demo