|
1 |
| -## Creating a special object for calculating properties of matrix |
2 |
| -## e.g. inverse with caching options |
3 |
| - |
4 |
| -## Class for creating matrices with |
5 |
| -## ability to cache results of operations |
6 |
| - |
7 |
| -CachedOpsMatrix <- setRefClass("CachedOpsMatrix", |
8 |
| - fields = list(value = "matrix" ), |
| 1 | +## Creating a special object for caching calculations |
| 2 | +# example: |
| 3 | +# m <- matrix(1:4,c(2,2)) |
| 4 | +# mci <- makeCacheMatrix({message("calculating");solve(m)}) |
| 5 | +# cacheSolve(mci) |
| 6 | +# cacheSolve(mci) # should not print message again, should insted inform about cache use |
| 7 | +# mcs <- makeCacheMatrix(solve(m,c(1,1)) |
| 8 | +# cacheSolve(mcs) |
| 9 | + |
| 10 | +# Class for creating matrices with |
| 11 | +# ability to cache results of operations |
| 12 | +# see CacheOps$help(getResult) |
| 13 | +CachedOps <- setRefClass("CachedOps", |
| 14 | + fields = list(result = "function", cached = "logical"), |
9 | 15 |
|
10 | 16 | methods = list(
|
11 |
| - initialize = function(...){ |
12 |
| - my.inverse <<- NULL |
| 17 | + initialize = function(expr,...){ |
| 18 | + cached <<- FALSE |
| 19 | + result <<- function(){ |
| 20 | + cached <<- TRUE |
| 21 | + expr |
| 22 | + } |
13 | 23 | callSuper(...)
|
14 | 24 | },
|
15 | 25 |
|
16 |
| - getInverse = function(){ |
17 |
| - "Calculating inverse of matrix. Once it was calculated result is cached and returned in any consecutive call" |
18 |
| - if(is.null(my.inverse)) |
19 |
| - my.inverse <<- solve(value) |
20 |
| - else message("getting cached data") |
21 |
| - my.inverse |
| 26 | + getResult = function(){ |
| 27 | + "Calculating result of operation on matrix. |
| 28 | +Once it was calculated result is cached and returned in any consecutive call" |
| 29 | + if(cached) message("getting cached data") |
| 30 | + result() |
22 | 31 | })
|
23 | 32 | )
|
24 | 33 |
|
25 |
| -## Creating new caching object |
26 |
| - |
27 |
| -makeCacheMatrix <- function(x = matrix()) { |
28 |
| - CachedOpsMatrix$new(value = x) |
| 34 | +makeCacheMatrix <- function(expr,...) { |
| 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(expr,...) |
29 | 40 | }
|
30 | 41 |
|
31 |
| - |
32 |
| -## Calculating inverse of matrix |
33 |
| -## once it was calculated result is cached |
34 |
| -## and returned in any consecutive call |
35 |
| - |
36 |
| -cacheSolve <- function(x, ...) { |
37 |
| - x$getInverse() |
| 42 | +cacheSolve <- function(x) { |
| 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() |
38 | 47 | }
|
0 commit comments