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.r200 chars12 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.r60 chars10 lines
Note that the memoisation technique can significantly improve the performance of recursive functions, especially when dealing with large input values.
gistlibby LogSnag