The R Project SVN R

Rev

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

Rev Author Line No. Line
8504 maechler 1
#### Testing  UseMethod() and even more NextMethod()
50986 maechler 2
#### -------------------- 
3
#### i.e.,  S3 methods *only*. For S4, see  reg-S4.R
4
##                                          ~~~~~~~~
8504 maechler 5
 
6
###-- Group methods
7
 
40086 ripley 8
## previous versions used print() and hit an auto-printing bug.
9
 
8504 maechler 10
### Arithmetic "Ops" :
40086 ripley 11
">.bar" <- function(...) {cat("using >.bar\n"); FALSE}
12
">.foo" <- function(...) {cat("using >.foo\n"); TRUE}
8504 maechler 13
Ops.foo <- function(...) {
40086 ripley 14
    cat("using Ops.foo\n")
8504 maechler 15
    NextMethod()
16
}
40086 ripley 17
Ops.bar <- function(...) {
18
    cat("using Ops.bar\n")
19
    TRUE
20
}
8504 maechler 21
 
22
x <- 2:4 ; class(x) <- c("foo", "bar")
23
y <- 4:2 ; class(y) <- c("bar", "foo")
24
 
25
## The next 4 give a warning each about incompatible methods:
26
x > y
27
y < x # should be the same (warning msg not, however)
28
x == y
29
x <= y
30
 
31
x > 3 ##[1] ">.foo"
32
 
33
rm(list=">.foo")
34
x > 3 #-> "Ops.foo" and ">.bar"
35
 
36
 
37
 
38
### ------------  was ./mode-methods.R till R ver. 1.0.x ----------------
39
 
40
###-- Using Method Dispatch on "mode" etc :
22734 jmc 41
## Tests S3 dispatch with the class attr forced to be data.class
42
## Not very relevant when S4 methods are around, but kept for historical interest
8504 maechler 43
abc <- function(x, ...) {
24536 ripley 44
    cat("abc: Before dispatching; x has class `", class(x), "':", sep="")
45
    str(x)
24517 ripley 46
    UseMethod("abc", x) ## UseMethod("abc") (as in S) fails
8504 maechler 47
}
48
 
49
abc.default <- function(x, ...) sys.call()
50
 
51
"abc.(" <- function(x)
52
    cat("'(' method of abc:", deparse(sys.call(sys.parent())),"\n")
53
abc.expression <- function(x)
54
    cat("'expression' method of abc:", deparse(sys.call(sys.parent())),"\n")
55
 
56
abc(1)
57
e0 <- expression((x))
58
e1 <- expression(sin(x))
59
abc(e0)
60
abc(e1)
61
abc(e0[[1]])
62
abc(e1[[1]])