From ripley at stats.ox.ac.uk  Fri May 19 17:01:21 2006
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Fri, 19 May 2006 16:01:21 +0100 (BST)
Subject: [Rd] UseMethod infelicity
Message-ID: <Pine.LNX.4.64.0605191348300.6158@gannet.stats.ox.ac.uk>

If I do

> example(lm)
...
> mycoef <- function(object, ...) UseMethod("coef", object)
> mycoef(lm.D9)
Error in mycoef(lm.D9) : no applicable method for "coef"

which is pretty surprising, as coef has a default method.

After a bit of digging, this comes from do_usemethod having

        defenv = environment where the generic was defined */
     defenv = ENCLOS(env);

so it is assuming that UseMethod() is called within the defining generic 
for its first argument.  That plainly does not need to be true, e.g.

> coefficients
function (object, ...)
UseMethod("coef")
<environment: namespace:stats>

It is clear to me that we need to search for 'generic' and find its 
defining environment rather than that of the current caller.  It is not 
entirely clear where to search from as I think we need to avoid

mycoef <- function(x)
{
    mycoef <- function(x) stop("not this one")
    UseMethod("mycoef")
}

so I used ENCLOS(env).

This adds some overhead, hopefully no more than searching for methods.

BTW, I noticed that R_LookupMethod uses findVar, that is looks for any 
object not for functions: that must be another infelicity.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



[Rd] UseMethod infelicity
Prof Brian Ripley