|
10 | 10 | # Class for creating matrices with
|
11 | 11 | # ability to cache results of operations
|
12 | 12 | CachedOps <- setRefClass("CachedOps",
|
13 |
| - fields = list( func = "function", cache = "ANY"), |
| 13 | + fields = list( func = "function", cache = "ANY"), |
14 | 14 |
|
15 |
| - methods = list( |
16 |
| - initialize = function(...,func){ |
17 |
| - cache <<- NULL |
18 |
| - func <<- function(){ |
19 |
| - func(...) |
20 |
| - } |
21 |
| - callSuper() |
22 |
| - }, |
| 15 | + methods = list( |
| 16 | + initialize = function(...,func){ |
| 17 | + cache <<- NULL |
| 18 | + func <<- function() func(...) |
| 19 | + callSuper() |
| 20 | + }, |
23 | 21 |
|
24 |
| - getResult = function(){ |
25 |
| - "Calculating result of operation on matrix. |
| 22 | + getResult = function(){ |
| 23 | + "Calculating result of operation on matrix. |
26 | 24 | Once it was calculated result is cached and returned in any consecutive call"
|
27 |
| - if(cached) message("getting cached data") |
28 |
| - result() |
29 |
| - }) |
30 |
| - ) |
| 25 | + if(is.null(cache)) { |
| 26 | + cache <<- func() |
| 27 | + }else{ |
| 28 | + message("getting cached data") |
| 29 | + } |
| 30 | + cache |
| 31 | + }) |
| 32 | + ) |
31 | 33 |
|
32 | 34 | makeCacheMatrix <- function(..., func = solve) {
|
33 |
| - # Creating new caching object |
34 |
| - # Args: |
35 |
| - # func - function, result of calculation is need to cache |
36 |
| - # ... - parameters for function calling |
37 |
| - CachedOps$new(..., func = func) |
| 35 | + # Creating new caching object |
| 36 | + # Args: |
| 37 | + # func - function, result of calculation is need to cache |
| 38 | + # ... - parameters for function calling |
| 39 | + CachedOps$new(..., func = func) |
38 | 40 | }
|
39 | 41 |
|
40 | 42 | cacheSolve <- function(x, ...) {
|
41 |
| - # Calculating result of function on matrix |
42 |
| - # once it was calculated result is cached |
43 |
| - # and returned in any consecutive call |
44 |
| - x$getResult() |
| 43 | + # Calculating result of function on matrix |
| 44 | + # once it was calculated result is cached |
| 45 | + # and returned in any consecutive call |
| 46 | + x$getResult() |
45 | 47 | }
|
0 commit comments