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.
3
5
4
- # # Write a short comment describing this function
5
6
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
+ }
7
23
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
+ }
8
40
}
9
41
10
42
11
- # # Write a short comment describing this function
43
+ # # Example to matrix to invert.
44
+ m <- matrix (c(2 , 5 , 1 , 2 ), 2 , 2 )
12
45
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