r-lib / memoise

Easy memoisation for R
https://memoise.r-lib.org
Other
317 stars 56 forks source link

Function to check if a function call is cached #112

Closed DavZim closed 4 years ago

DavZim commented 4 years ago

Is it possible to have a function is_cached that checks if a call is already in the cache?

Something like this (doesn't work, as I don't fully understand the internals of memoise()).

is_cached <- function(f, ...) {
  stopifnot(is.memoised(f))

  args <- list(...)

  cc <- environment(f)$`_cache`
  cc$has_key(cc$digest(c(body(f), args)))
}

myfun <- memoise(function(name = "Alice") print(paste("Hello", name)))
myfun("Alice")

is_cached(myfun, "Alice") # TRUE
is_cached(myfun, name = "Alice") # TRUE
is_cached(myfun, name = "Bob") # FALSE

Even better: if the is_cached function is able to take the call to the memoised function is_cached(myfun("Alice")).

jimhester commented 4 years ago

memoise::has_cache()?

DavZim commented 4 years ago

I didn't see that! Works as expected. Thanks for the hint!