File: method-dispatch.R

package info (click to toggle)
r-base 2.4.0.20061125-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 53,384 kB
  • ctags: 27,223
  • sloc: ansic: 228,006; fortran: 76,848; sh: 12,670; perl: 9,489; makefile: 6,064; tcl: 2,954; yacc: 2,152; java: 486; cpp: 457; asm: 275; sed: 16
file content (56 lines) | stat: -rw-r--r-- 1,365 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#### Testing  UseMethod() and even more NextMethod()
####

###-- Group methods

### Arithmetic "Ops" :
">.bar" <- function(...) print(">.bar")
">.foo" <- function(...) print(">.foo")
Ops.foo <- function(...) {
    print("Ops.foo")
    NextMethod()
}
Ops.bar <- function(...)
    print("Ops.bar")

x <- 2:4 ; class(x) <- c("foo", "bar")
y <- 4:2 ; class(y) <- c("bar", "foo")

## The next 4 give a warning each about incompatible methods:
x > y
y < x # should be the same (warning msg not, however)
x == y
x <= y

x > 3 ##[1] ">.foo"

rm(list=">.foo")
x > 3 #-> "Ops.foo" and ">.bar"



### ------------  was ./mode-methods.R till R ver. 1.0.x ----------------

###-- Using Method Dispatch on "mode" etc :
## Tests S3 dispatch with the class attr forced to be data.class
## Not very relevant when S4 methods are around, but kept for historical interest
abc <- function(x, ...) {
    cat("abc: Before dispatching; x has class `", class(x), "':", sep="")
    str(x)
    UseMethod("abc", x) ## UseMethod("abc") (as in S) fails
}

abc.default <- function(x, ...) sys.call()

"abc.(" <- function(x)
    cat("'(' method of abc:", deparse(sys.call(sys.parent())),"\n")
abc.expression <- function(x)
    cat("'expression' method of abc:", deparse(sys.call(sys.parent())),"\n")

abc(1)
e0 <- expression((x))
e1 <- expression(sin(x))
abc(e0)
abc(e1)
abc(e0[[1]])
abc(e1[[1]])