The R Project SVN R

Rev

Rev 24517 | Rev 50986 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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