-
Notifications
You must be signed in to change notification settings - Fork 56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A cache function to cache arbitrary R code #40
base: main
Are you sure you want to change the base?
Conversation
@hadley this is not exactly the API you were prototyping as it does not take a filename parameter, instead the filenames (if you are using the filesystem backend) are a hash of the function body. |
#' @export | ||
cache <- function(code, ..., envir = parent.frame(), cache = cache_memory()) { | ||
expr <- substitute(code) | ||
key <- cache$digest(c(expr, lapply(list(...), function(x) eval(x[[2L]], environment(x))))) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is the eval necessary here? Won't list(...)
force all the promises?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh because they're formulas
R/cache.R
Outdated
f <- function() NULL | ||
body(f) <- expr | ||
environment(f) <- envir | ||
(memoise(f, envir = envir, ..., cache = cache))() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not just do cache$set(key, f())
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good question!
This is a proof of concept, caching arbitrary R code.
This uses the existing memoise machinery to compute a hash based on the input code / expression and any additional variables (specified as formulas in
...
), so does not take a cache filename.You can use it with the in-memory cache, but you need to specify the cache up front, otherwise a new cache is created on every invocation.
Improvements would be to use rlang to construct the function and quote the code / extra arguments. We would also need to change how the
...
arguments are handled in regular memoise to userlang::dots_quos()
andrlang::tidy_eval()
.