[R] 2 setGeneric's, same name, different method signatures

Greg Minshall minshall at umich.edu
Fri Feb 15 12:35:08 CET 2013


Martin,

fantastic.  thank you *very* much!  that clears lots of things up for
me.

(for the record: i think that setGeneric overwriting a previous is more
surprising -- thus violating the principle of least surprise -- than one
function overwriting a previous, in that we think of (or, one way to
think of) OOP is that, after finagling to have no clashes on *class*
names, we should not worry about other than intra-class name clashes.
as i said, for the record.)

thanks again.

cheers, Greg
----
Martin Morgan <mtmorgan at fhcrc.org> wrote:
> 
> Hi Greg --
> 
> this setGeneric is over-writing the first, as would
> 
> f = function() "first"
> f = function() "second"
> f() # "second"
> 
> If you'd like to dispatch on a single argument, then
> 
> setGeneric("one", function(x, ...) standardGeneric("one"))
> setMethod("one", "A", function(x, ...) "A-method")
> setMetohd("one", "B", function(x, y, ...) "B-method")
> 
> The '...' in the generic allow you to add arguments that are 'picked
> off' by methods. The user could provide any value for y, not only an
> object of class "B".
> 
> If you'd like to dispatch sometimes on two arguments then
> 
> setGeneric("two", function(x, y, ...) standardGeneric("two"))
> setMethod("two", c("A", "ANY"), function(x, y, ...) "A,ANY-method")
> setMethod("two", c("B", "B"), function(x, y, ...) "B,B-method")
> 
> then two(new("A")), two(new("A"), new("A")) and two(new("A"),
> new("B")) end up in A,ANY,two-method while two(new("B"), new("B"))
> ends up in "B,B,two-method". Other combinations are errors. One might
> instead not define A,ANY but instead
> 
> setMethod("two", c("A", "missing"), function(x, y, ...) "A,missing-method")
> 
> and then two(new("A"), new("A")) would be an error.
> 
> Multiple dispatch is complicated, and perhaps best to avoid if possible.
> 
> It's possible to write a generic and methods that dispatch on '...',
> with the requirement that all classes are the same; this in the spirit
> of comparing two B's and returning the smaller; see ?dotsMethods
> though again this is not a trivial use case.
> 
> Hope that helps enough.
> 
> Martin



More information about the R-help mailing list