Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit cb94cb7

Browse files
committed
Add lazy loader and cached func factory.
1 parent 7f657dd commit cb94cb7

File tree

1 file changed

+45
-8
lines changed

1 file changed

+45
-8
lines changed

cachematrix.R

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,52 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## This solution ignores the one required by the assignment. I believe this
2+
## solution is more flexible. That one is working with fixed function and
3+
## arguments.
4+
## This code presents two alternatives.
35

4-
## Write a short comment describing this function
56

6-
makeCacheMatrix <- function(x = matrix()) {
7+
## Creates a version of a function that is able to cache the result per key.
8+
## This allows making a cachable version of any function.
9+
## Useful when the calling arguments are expected to change.
10+
## Input
11+
## - f function
12+
## Return
13+
## - callable function, arguments: cache key, original function arguments
14+
cachedFunctionFactory <- function(f) {
15+
cache = list()
16+
function(key, ...) {
17+
if (is.null(cache[[key]])) {
18+
cache[[key]] <<- f(...)
19+
}
20+
cache[[key]]
21+
}
22+
}
723

24+
## Lazy loader generator.
25+
## Accepts any function with the called arguments.
26+
## Useful when the arguments will not change.
27+
## Input
28+
## - f function
29+
## - ... function args
30+
## Return
31+
## - callable lazy evaluator
32+
lazyLoadingFactory <- function(f, ...) {
33+
cache = NULL
34+
function() {
35+
if (is.null(cache)) {
36+
cache <<- f(...)
37+
}
38+
cache
39+
}
840
}
941

1042

11-
## Write a short comment describing this function
43+
## Example to matrix to invert.
44+
m <- matrix(c(2, 5, 1, 2), 2, 2)
1245

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}
46+
## Example of using the cached function loader:
47+
cachableSolve <- cachedFunctionFactory(solve)
48+
cachedSolve("key", m)
49+
50+
## Example of using the lazy loader:
51+
lazySolve <- lazyLoadingFactory(solve, m)
52+
lazySolve()

0 commit comments

Comments
 (0)