R's UseMethod() does not dispatch on changed class() (PR#167)

Bill Venables wvenable@arcola.stats.adelaide.edu.au
Fri, 16 Apr 1999 15:50:54 +0930 (CST)


Well, I have to admit that I have egg all over my face this
time, and if you don't want to have the long-winded justification
I suggest you pass to your next email...

--

In my defence I was misled by what can only be called an S3 bug,
now probably unfixable since some code probably depends on it.
Here is the most succinct expression of it I can devise:

S3:

foo <- function(x) {
  class(x) <- "bar"
  x <- x - 1
  UseMethod("foo")
}
foo.bar <- function(x) invisible(print(x))


Now with one kind of actual argument method dispatch occurs, but
he *original* value is passed on:

> foo(10)
[1] 10

but with any other kind the *modified* value is passed:

> fred <- 10
> foo(fred)
[1] 9
attr(, "class"):
[1] "bar"

and most egregiously:

> foo((10))
[1] 9
attr(, "class"):
[1] "bar"



On the other hand in S4 this anomaly is at least fixed.

S4 (using backward compatibility):

foo <- function(x) {
  oldClass(x) <- "bar"
  x <- x - 1
  UseMethod("foo")
}
foo.bar <- function(x) invisible(print(x))

> foo(10)
[1] 9
attr(, "class"):
[1] "bar"
> foo((10))
[1] 9
attr(, "class"):
[1] "bar"

There are other differences with S3, though.  For example, local
variables generated in the frame of the generic *are* passed to
the method in S3, but *are not* passed to the method in S4.

What a mess!

One clear moral seems to be don't do anything more inside a
generic function than you really need to do.  Keep it *very*
simple indeed.


I'm grateful to you guys for bringing up this matter right now,
but I'm sorry to be working it all out in front of you like this!

Bill Venables.
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._