1
\$\begingroup\$

Here is what I came to for calculation result caching/invalidating. What do you think?

How to use:

m <- matrix(1:4, 2, 2)

# note that adding properties to calculate/store
# do not require code modifications
c <- cache(m, min=min, max=max, solve=solve)
print(c$get())
print(c$min())
print(c$max())
print(c$solve())

#prints cached result
print(c$max())

#resets cache
c$set(t(m))
print(c$get())
print(c$min())
print(c$max())
print(c$solve())

Implementation:

lazy <- function(FUN, ...) {
    .val <- NULL
    function()
        if(is.null(.val))
            .val <<- FUN(...)
        else
            .val
}

cache <- function(value, ...) {
    this <- NULL
    set <- function(value) {
        this <<- lapply(list(...), lazy, value)
        this$get <<- function() value
        this$set <<- function(value) set(value)
    }
    set(value)    
    lapply(setNames(nm = names(this)), 
           function(f) function(...) this[[f]](...))
}

Not quite sure about last dispatching lapply. Do you know an easy way? (My first days in R...)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.