[Rd] generics for primitive functions
John Chambers
jmc at r-project.org
Sat Sep 23 15:35:34 CEST 2006
Probably a bug, but not at all the one you imply. You have found a way
to subvert a guarantee in R that methods for primitives can never be
redefined for basic data types.
As you no doubt found, but didn't show us, so long as you say sqrt(4)
the result is correct. (Your "Works" should really read "Gotcha!").
Since a large amount of effort and not a little programming pain has
been spent retaining the purity of primitive calls to satisfy the
efficiency lobby, it's not clear what should happen when one insists on
calling the generic function directly. Either an error or just a call
to the primitive would be the two likely candidates. Not what happens
in your first example though.
If you really want a "numeric" class that does something different for
sqrt(), define an S4 class that contains "numeric"
> setClass("WeirdNumber", contains="numeric")
[1] "WeirdNumber"
> setMethod("Math", "WeirdNumber", function(x) "Weird")
[1] "Math"
> xx = new("WeirdNumber", 1:10)
> sqrt(xx)
[1] "Weird"
Parlamis Franklin wrote:
> i think these two code snippets exhibit a bug. they are identical
> but for the inclusion of an initial line in snippet [2]
>
> [1]
> setMethod("Math", signature(x = "numeric"), function(x) "Works")
> getGeneric("sqrt")(4)
>
> [2]
> getGeneric("sqrt")(4)
> setMethod("Math", signature(x = "numeric"), function(x) "Works")
> getGeneric("sqrt")(4)
>
> these are my results, when each is run from a fresh R session
>
> [1]
> > setMethod("Math", signature(x = "numeric"), function(x) "Works")
> [1] "Math"
> > getGeneric("sqrt")(4)
> [1] "Works"
>
> [2]
> > getGeneric("sqrt")(4)
> `__Deferred_Default_Marker__`
> > setMethod("Math", signature(x = "numeric"), function(x) "Works")
> [1] "Math"
> > getGeneric("sqrt")(4)
> `__Deferred_Default_Marker__`
>
> the section in "How Methods Work" that deals with this is unfinished,
> but i think it suggests that getGeneric("sqrt")(4) should work out of
> the box.
>
> franklin parlamis
>
> > version
> _
> platform powerpc-apple-darwin8.7.0
> arch powerpc
> os darwin8.7.0
> system powerpc, darwin8.7.0
> status beta
> major 2
> minor 4.0
> year 2006
> month 09
> day 22
> svn rev 39471
> language R
> version.string R version 2.4.0 beta (2006-09-22 r39471)
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>
More information about the R-devel
mailing list