diff --git a/DESCRIPTION b/DESCRIPTION index 94b3e04..d652cff 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -19,6 +19,7 @@ Suggests: aws.s3, httr, covr, + googleAuthR, googleCloudStorageR License: MIT + file LICENSE RoxygenNote: 6.1.0 diff --git a/R/memoise.R b/R/memoise.R index 48915d5..f2bc63e 100644 --- a/R/memoise.R +++ b/R/memoise.R @@ -122,6 +122,9 @@ memoise <- memoize <- function(f, ..., envir = environment(f), cache = cache_mem args <- c(lapply(called_args, eval, parent.frame()), lapply(default_args, eval, envir = environment())) + # Replace memoised functions in arguments with their original bodies + args <- lapply(args, function(x) if (memoise::is.memoised(x)) as.character(body(environment(x)$`_f`)) else x) + hash <- encl$`_cache`$digest( c(as.character(body(encl$`_f`)), args, lapply(encl$`_additional`, function(x) eval(x[[2L]], environment(x)))) @@ -147,7 +150,7 @@ memoise <- memoize <- function(f, ..., envir = environment(f), cache = cache_mem # This should only happen for primitive functions if (is.null(envir)) { - envir <- baseenv() + envir <- baseenv() } memo_f_env <- new.env(parent = envir) @@ -261,7 +264,7 @@ has_cache <- function(f) { # Modify the function body of the function to simply return TRUE and FALSE # rather than get or set the results of the cache body <- body(f) - body[[9]] <- quote(if (encl$`_cache`$has_key(hash)) return(TRUE) else return(FALSE)) + body[[10]] <- quote(if (encl$`_cache`$has_key(hash)) return(TRUE) else return(FALSE)) body(f) <- body f @@ -288,7 +291,7 @@ drop_cache <- function(f) { # Modify the function body of the function to simply drop the key # and return TRUE if successfully removed body <- body(f) - body[[9]] <- quote(if (encl$`_cache`$has_key(hash)) { + body[[10]] <- quote(if (encl$`_cache`$has_key(hash)) { encl$`_cache`$drop_key(hash) return(TRUE) } else { diff --git a/tests/testthat/test-memoise.R b/tests/testthat/test-memoise.R index 89ccac1..eb32d36 100644 --- a/tests/testthat/test-memoise.R +++ b/tests/testthat/test-memoise.R @@ -246,6 +246,21 @@ test_that("argument names don't clash with names in memoised function body", { expect_identical(f(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), f_mem(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) }) +test_that("other memoised function passed as arguments", { + f <- function(x) x + g <- function(fn) {i <<- fn(i) + 1; i} + i <- 0 + + fm <- memoise(f) + gm <- memoise(g) + + expect_equal(g(fm), 1) + expect_equal(gm(fm), 2) + expect_equal(gm(fm), 2) + expect_equal(g(fm), 3) + expect_equal(gm(fm), 2) +}) + context("has_cache") test_that("it works as expected with memoised functions", { mem_sum <- memoise(sum)