fib_mem_factory <- function() {
## the memo-sheet:
memo <- list()
function(n) {
# names of list-elements are strings:
key <- as.character(n)
if (!is.null(memo[[key]])) {
# woo-hoo, we hit the memo-sheet!
return(memo[[key]])
}
if (n %in% c(1, 2)) {
# we are at a base case, so add this info to the memo sheet:
memo[[key]] <<- 1
return(1)
}
new_fib <- Recall(n - 2) + Recall(n - 1)
# record the result in the memo sheet:
memo[[key]] <<- new_fib
# return the result:
new_fib
}
}