Skip to content

Instantly share code, notes, and snippets.

@JonasMoss
Created February 18, 2018 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonasMoss/edb4a77a659ea155cde03555dd2b8967 to your computer and use it in GitHub Desktop.
Save JonasMoss/edb4a77a659ea155cde03555dd2b8967 to your computer and use it in GitHub Desktop.
Using functors to memoize a function in R.
## Functor example 1: Memoization.
## We memoize a function g with up to N values.
## The function to memoize: It is slow to calculate, so we'll gain from
## storing its values.
g = function(x) {
Sys.sleep(0.1)
print("Processesing ...")
x^2
}
## The setup that does the memoization. It will store up to precompute_N values,
## starting over when the edge is met. More sophisticated methods are possible.
precompute_N = 100
f = function(x) {
## Memoize values:
if(x %in% f$precomputed_names) {
index = which(x == f$precomputed_names)
return(f$precomputed[[index]])
}
y = g(x)
precomputed_index = (f$precompute_index + 1) %% precompute_N
f$precompute_index = precomputed_index
f$precomputed[[precomputed_index]] = y
f$precomputed_names[[precomputed_index]] = x
y
}
class(f) = "f"
## We will need some generics and some members of the f-environment.
`$.f` = function(f, y) environment(f)[[y]]
`$<-.f` = function(f, y, value) {
environment(f)[[y]] = value
invisible(f)
}
environment(f) = new.env()
environment(f)$precomputed = as.list(rep(NA, precompute_N))
environment(f)$precomputed_names = as.list(rep(NA, precompute_N))
environment(f)$precompute_index = 0
## Testing:
f(3)
f(3)
f(3)
f(5)
f(5)
f(5)
f(7)
f(7)
f(7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment