memo

0th

Percentile

Memo

Creates a memoized function, based on the provided named or anonymous function. Calls to the memoized function will be retrieved from a cache, unless it is the first time it is called.

Passing memo.force = TRUE to the memo function call will by-pass any previously cached values and execute the underlying function, storing the newly retrieved values for subsequent calls. memo.force = FALSE by default.

Passing memo.dryrun = TRUE to the memo function call will prevent the underlying function from executing and return TRUE if call isn't caches and FALSE if it is. These values are not cached as responses for the function.

Note that results are cached based on the argument values passed to the function. The order is not important since all names are resolved. So fun(a=1, b=2) will return the same cached value as fun(b=2, a=1), for example.

Functions as arguments are supported, but only the body is compared. So a named function parameter and an anonymouse function parameter with the same body, will be evaluated as identical and return the same cached value.

... is supported, but note that unless named then the order of the values is significant and will produce different cache values unless identical.

By default NULL values are not cached. Setting allow.null=TRUE when creating the memo will, however, ensure that NULL values are cached.

Usage
memo(f, allow.null = FALSE)
Arguments
f

function to memoise

allow.null

if TRUE then the memoed function will cache NULL results, otherwise it won't. FALSE by default.

Value

the memoed function

Aliases
  • memo
Examples
# NOT RUN {
library(magrittr)

# a simple example function
simple.function <- function (value) {
  print("Executing!")
  value
}

# call memo function to memoise a function
simple.function.memo <- memo(simple.function)

# or like this
simple.function %<>% memo()

# or use an anon function
simple.function2 <- (function (value) value) %>% memo()

# the first time we call the memo the function will execute
simple.function(10)

# if we call the memo again with the same parameter values then
# the cached value will be returned
simple.function(10)

# calling the memo with a different set of parameter values will
# cause the function to execute
simple.function(20)

# consider a slow function which is memoised, note that we have used the allow.null argument
# so that NULL is cached when returned from a function, the default is FALSE
slow.function <- (function (value) Sys.sleep(value)) %>% memo(allow.null = TRUE)

# the first time we call the slow function it takes some time
system.time(slow.function(3))

# subsequent calls make use of the cache and are much faster
system.time(slow.function(3))
# }
Documentation reproduced from package memofunc, version 1.0.2, License: GPL-3

Community examples

Looks like there are no examples yet.