Search code examples
rmemoizationmemoise

Load current cache using memoise


Let's assume I have run a memoised function that returns an integer output. Now, I do not know what inputs were used to store the current cache. Is there any way that I can get the current integer output that has been cached if using the memoise package?

Below is some minimalistic code:

library(memoise)
fn <- function(x) x+5
fn_mem <- memoise(fn)
a <- fn_mem(5)

Now assume for some reason, I have lost the variable a and don't remember that fn_mem was run with input parameter 5 but still need to know what the output was when fn_mem was run.

Is it possible to get the currently cached result in such a case?


Solution

  • One can define the following function, which takes a memoised function and returns the result of its last evaluation:

    getLast <- function(fn){
        stopifnot(class(fn) == c("memoised", "function"))
        keys <- get("_cache", envir=environment(fn))$keys()
        n <- length(keys)
        get("_cache", envir=environment(fn))$get(keys[n])[[1]]
    }
    

    Example:

    library(memoise)
    fn <- function(x) x*10
    fn_mem <- memoise(fn)
    fn_mem(1)
    [1] 10
    getLast(fn_mem)
    [1] 10
    
    fn_mem(7)
    [1] 70
    getLast(fn_mem)
    [1] 70