create a memoised function to add two numbers in r

Here's an example of a memoized function to add two numbers in R. Memoization is a technique used to reduce the number of times a function is called by caching the result of its computation.

# create a memoization environment
memo_env <- new.env()

# create a function to memoize
add <- function(a, b){
  
  # create a unique key for the cached result
  key <- paste0(a, "_", b)
  
  if(key %in% names(memo_env)){
    # if result is already in cache, return the cached result
    return(memo_env[[key]])
  } else {
    # if result is not in cache, perform the computation and store the result in cache
    result <- a + b
    memo_env[[key]] <- result
    return(result)
  }
}

# test the function
add(2, 3) # returns 5
add(2, 3) # returns 5 (cached result)
567 chars
24 lines

In this example, we create a memoization environment memo_env using the new.env() function. The add() function takes two arguments a and b, and checks if the result is already in cache using the key value which is generated by concatenating the arguments with an underscore. If the result is in cache, the cached result is returned. If the result is not in cache, the computation is performed, and the result is stored in cache.

gistlibby LogSnag