moodymudskipper / tags

A collection of tags built using the package tag
GNU General Public License v3.0
8 stars 0 forks source link

can we memoise ? #29

Open moodymudskipper opened 5 years ago

moodymudskipper commented 5 years ago

With Jim Hester's memoise package one has to define a new function, can we find a solution to memoise a call so we can call memoising$fun(foo) ?

moodymudskipper commented 5 years ago

It works!

# should be set in .onLoad 
options(tags.mmemoise = memoise::memoise(memoise::memoise))
options(tags.cache = memoise::cache_memory())

memoising <- tag::tag(
  args = alist(restrictions = list(), envir = NULL, cache = getOption("tags.cache")), 
  pattern = {
  if (!requireNamespace("memoise")) 
    stop("Install the memoise package to use the tag 'memoising'")
  #f_memoised <- memoise::memoise(f, cache = cache_path)
  call <- CALL(eval = FALSE)
  if(is.null(envir)) envir = environment(f)
  # in order for our code to work memoise needs to be itself memoised 
  # so we can call `mmemoise` several time with the same params and get the same
  # result. `mmemoise` is initiated on load.
  call[[1]] <- rlang::expr(getOption("tags.mmemoise")(
    !!call[[1]], !!!restrictions, envir = !!envir, cache = !!substitute(cache)))
  eval.parent(call)
})

n <- 4
set.seed(1)
memoising$runif(n)
#> [1] 0.2655087 0.3721239 0.5728534 0.9082078
set.seed(2)
memoising$runif(n)
#> [1] 0.2655087 0.3721239 0.5728534 0.9082078
foo <- runif
memoising$foo(n)
#> [1] 0.2655087 0.3721239 0.5728534 0.9082078
n <- n - 1
memoising$foo(n)
#> [1] 0.1848823 0.7023740 0.5733263
n <- n + 1
memoising$foo(n)
#> [1] 0.2655087 0.3721239 0.5728534 0.9082078

Created on 2019-08-28 by the reprex package (v0.3.0)