[R] fun with S4 method recursion
Ross Boylan
ross at biostat.ucsf.edu
Wed Jun 8 02:15:44 CEST 2005
Apparently using an existing function as the definition for a method is
a no-no (at least as I'm doing it), producing infinite recursion.
setClass("A",
representation(model="ANY")
)
fiddle <- function(self) {
1
}
setMethod("fiddle",
signature(self="A"),
definition = fiddle ### problem
)
setClass("B",
representation(err="ANY"),
contains="A"
)
setMethod("fiddle",
signature(self="B"),
definition = function(self){
callNextMethod()
2
})
b <- new("B", model=4, err=5)
fiddle(b)
produces
Error: protect(): protection stack overflow
On the other hand, if the line marked ### problem becomes
definition = function(self) 1
everything works OK.
I think the definition of the generic is ending up as the method for A.
This surprised me, because I thought this was the standard way to
approach setting up a method ("Any ordinary function can be converted
into a generic by simply setting a method for it; ... the initial,
unique method (the body of the function) becomes the default method" pp.
322-323; "a generic function is created automatically by specifying a
method for any existing function. This is by far the more common
situation" p 348--all pages in the green book). It also surprised me
because of the note that setMethod makes a local copy of the function
given as the definition argument (bottom of p. 323).
Does the behavior of R differ from that described in the green book when
the name of a function appears in the definition argument of setMethod?
If not, what have I misunderstood?
Aside: my first real attempt didn't have
fiddle <- function(self) {1}
using just
setMethod("fiddle", "A", function(self) 1)
That produces no existing definition for function 'fiddle'
Given all this, would this be a better model?
fiddle <- function(... # definition for A
# do NOT setMethod for class A signature
setMethod("fiddle", "B", function(self) #operations for B
So when I do the setMethod my original fiddle becomes the default
generic.
Thanks.
Ross
More information about the R-help
mailing list