From cb94cb70ec113b164ea156c2961b7cdcf7391fcf Mon Sep 17 00:00:00 2001 From: Peter Arato Date: Tue, 20 Jan 2015 22:32:02 +0000 Subject: [PATCH] Add lazy loader and cached func factory. --- cachematrix.R | 53 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/cachematrix.R b/cachematrix.R index a50be65aa44..ec894900def 100644 --- a/cachematrix.R +++ b/cachematrix.R @@ -1,15 +1,52 @@ -## Put comments here that give an overall description of what your -## functions do +## This solution ignores the one required by the assignment. I believe this +## solution is more flexible. That one is working with fixed function and +## arguments. +## This code presents two alternatives. -## Write a short comment describing this function -makeCacheMatrix <- function(x = matrix()) { +## Creates a version of a function that is able to cache the result per key. +## This allows making a cachable version of any function. +## Useful when the calling arguments are expected to change. +## Input +## - f function +## Return +## - callable function, arguments: cache key, original function arguments +cachedFunctionFactory <- function(f) { + cache = list() + function(key, ...) { + if (is.null(cache[[key]])) { + cache[[key]] <<- f(...) + } + cache[[key]] + } +} +## Lazy loader generator. +## Accepts any function with the called arguments. +## Useful when the arguments will not change. +## Input +## - f function +## - ... function args +## Return +## - callable lazy evaluator +lazyLoadingFactory <- function(f, ...) { + cache = NULL + function() { + if (is.null(cache)) { + cache <<- f(...) + } + cache + } } -## Write a short comment describing this function +## Example to matrix to invert. +m <- matrix(c(2, 5, 1, 2), 2, 2) -cacheSolve <- function(x, ...) { - ## Return a matrix that is the inverse of 'x' -} +## Example of using the cached function loader: +cachableSolve <- cachedFunctionFactory(solve) +cachedSolve("key", m) + +## Example of using the lazy loader: +lazySolve <- lazyLoadingFactory(solve, m) +lazySolve() \ No newline at end of file