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.
567 chars24 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