memoise
memoise copied to clipboard
Nested functions are not hashed
Not sure if this is on purpose or too complicate to implement, but I wanted to document it here (as I couldn't find existing documentation/issues on it).
When we memoise a function that calls another function, the code of "other function" is not taken into account when creating the hash.
Eg.
cache <- cachem::cache_mem()
#####################################
# Base case ==============
foo <- function(x) {
bar(x)
}
bar <- function(x) {
x + 1
}
foo_mem <- memoise::memoise(foo, cache = cache)
memoise::has_cache(foo_mem)(1)
#> [1] FALSE
# expected!
foo_mem(1)
memoise::has_cache(foo_mem)(1)
#> [1] TRUE
# expected!
#####################################
# Case 1: change foo ===========
foo <- function(x) {
print("Running foo") # this was added
bar(x)
}
bar <- function(x) {
x + 1
}
foo_mem <- memoise::memoise(foo, cache = cache)
# foo_mem(1) is not cached because foo has changed: this is expected!
memoise::has_cache(foo_mem)(1)
#> [1] FALSE
# expected!
foo_mem(1)
memoise::has_cache(foo_mem)(1)
#> [1] TRUE
# expected!
#####################################
# Case 2: dependent function changes - change bar ========
foo <- function(x) {
print("Running foo")
bar(x)
}
bar <- function(x) {
print("Running bar") # this was added
x + 1
}
foo_mem <- memoise::memoise(foo, cache = cache)
memoise::has_cache(foo_mem)(1)
#> [1] TRUE
# NOT EXPECTED!
Ideally, I would expect the last foo_mem() to not have a cache, as bar() (inside foo()) has changed.