The R Project SVN R

Rev

Rev 54339 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
54339 jmc 1
mEditor <- setRefClass("matrixEditor",
2
      fields = list( data = "matrix",
3
        edits = "list"),
4
      methods = list(
5
     edit = function(i, j, value) {
6
       ## the following string documents the edit method
7
       'Replaces the range [i, j] of the
8
        object by value.
9
        '
10
         backup <-
11
             list(i, j, data[i,j])
12
         data[i,j] <<- value
13
         edits <<- c(edits, list(backup))
14
         invisible(value)
15
     },
16
     undo = function() {
17
       'Undoes the last edit() operation
18
        and update the edits field accordingly.
19
        '
20
         prev <- edits
21
         if(length(prev)) prev <- prev[[length(prev)]]
22
         else stop("No more edits to undo")
23
         edit(prev[[1]], prev[[2]], prev[[3]])
24
         ## trim the edits list
25
         length(edits) <<- length(edits) - 2
26
         invisible(prev)
27
     }
28
     ))
29
 
30
xMat <- xEdited <- matrix(as.double(1:12),4,3)
31
xEdited[[2,2]] <- 0
32
xx <- mEditor$new(data = xMat)
33
xx$edit(2, 2, 0)
34
stopifnot(identical(xx$data, xEdited))
35
xEdited[[1,3]] <- -1
36
xx$edit(1,3, -1)
37
stopifnot(identical(xx$data, xEdited))
38
xx$undo()
39
xEdited[[1,3]] <- xMat[[1,3]]
40
stopifnot(identical(xx$data, xEdited))
41
xx$undo()
42
stopifnot(identical(xx$data, xMat))
55578 jmc 43
 
44
## the tracing method
45
xx$trace(edit, quote(value <- 0))
46
xx$edit(2,2, -1) # traced should assign 0
47
stopifnot(identical(xx$data, xEdited))
48
xx$untrace(edit)
49
xx$edit(1, 3, -1) # now it should use -1
50
xEdited[[1,3]] <- -1
51
stopifnot(identical(xx$data, xEdited))