How do I understand this R function?

mfibR <- local({
    memo <- c(1, 1, rep(NA, 1000))
    f <- function(x) {
        if (x == 0) 
            return(0)
        if (x < 0) 
            return(NA)
        if (x > length(memo)) 
            stop("x too big for implementation")
        if (!is.na(memo[x])) 
            return(memo[x])
        ans <- f(x - 2) + f(x - 1)
        memo[x] <<- ans
        ans
    }
})

It does not have a function body, but it actually returns the Fibonacci sequence correctly.

+4
source share
1 answer

from the ?localman page.

local evaluates the expression in the local environment. This is equivalent to evalq, except that its default argument creates a new, empty Environment. This is useful for creating anonymous recursive functions and as a kind of limited namespace function, since variables defined in the environment are not visible from the outside.

local. , . local .

+5

All Articles