memoise fibonacci in r

One approach to memoise the Fibonacci function in R is to use a dynamic programming technique known as memoisation. In memoisation, we store the results of expensive function calls and return the cached result when the same inputs occur again.

Here is an example implementation of a memoised Fibonacci function in R:

main.r
fib <- local({
  cache <- c(0, 1)
  function(n) {
    if(n <= length(cache)) {
      return(cache[n])
    }
    fib_n <- fib(n - 1) + fib(n - 2)
    cache <<- c(cache, fib_n)
    return(fib_n)
  }
})
200 chars
12 lines

The function fib has an inner local function where we define a cache vector cache that stores previously computed Fibonacci numbers. If the requested Fibonacci number is already in the cache, we return it. Otherwise, we compute it recursively and store it in the cache for future use.

Using this memoised version of the Fibonacci function, we can quickly compute the nth Fibonacci number without redundant function calls:

main.r
> fib(10)
[1] 55

> fib(20)
[1] 6765

> fib(30)
[1] 832040

60 chars
10 lines

Note that the memoisation technique can significantly improve the performance of recursive functions, especially when dealing with large input values.

gistlibby LogSnag