Reputation: 94202
Can I create an S4 superclass of "function" and access the slots of that object from the function call? At the moment I have:
> setClass("pow",representation=representation(pow="numeric"),contains="function")
[1] "pow"
> z=new("pow",function(x){x^2},pow=3)
> z(2)
[1] 4
Now what I really want is for the function to be x to the power of the @pow slot of itself, so if I then do:
> z@pow=3
I get cubes, and if I do:
> z@pow=2
I get squares.
But I don't see how to get a reference to 'self' like I would do in Python. I'm guessing its somewhere in the environment somewhere...
Here's how it works in python:
class Pow:
def __init__(self,power):
self.power=power
self.__call__ = lambda x: pow(x,self.power)
p = Pow(2) # p is now a 'squarer'
print p(2) # prints 4
p.power=3 # p is now a 'cuber'
print p(2) # prints 8
Couldn't really be easier, and I didn't even have to do "import antigravity"....
Upvotes: 3
Views: 870
Reputation: 128
It seems that the parent function can be accessed via sys.function
.
setClass("pow", slots = c(pow = "numeric"), contains = "function")
z <- new("pow", function (x) x^(sys.function()@pow), pow = 2)
z(6)
# [1] 36
z@pow <- 3
z(6)
# [1] 216
I don't know whether sys.function
exists when this question was firstly discussed, though.
Upvotes: 0
Reputation: 46866
Resorting to a little language manipulation
setClass("Pow", representation("function", pow="numeric"),
prototype=prototype(
function(x) {
self <- eval(match.call()[[1]])
x^self@pow
}, pow=2))
and then
> f = g = new("Pow")
> g@pow = 3
> f(2)
[1] 4
> g(2)
[1] 8
although as Spacedman says things can go wrong
> f <- function() { Sys.sleep(2); new("Pow") }
> system.time(f()(2))
user system elapsed
0.002 0.000 4.005
A little more within the lines but deviating from the problem specification and probably no less easy on the eyes is
setClass("ParameterizedFunFactory",
representation(fun="function", param="numeric"),
prototype=prototype(
fun=function(x, param) function(x) x^param,
param=2))
setGeneric("fun", function(x) standardGeneric("fun"))
setMethod(fun, "ParameterizedFunFactory",
function(x) x@fun(x, x@param))
with
> f = g = new("ParameterizedFunFactory")
> g@param = 3
> fun(f)(2)
[1] 4
> fun(g)(2)
[1] 8
Upvotes: 3
Reputation: 263352
I think it depends what you really want. Is this implementation any closer to your goal?
setClass("pow",representation=representation(pow="numeric"),contains="function")
z=new("pow",function(x, pow=3){x^pow})
> z(2)
[1] 8
z(2,4)
#[1] 16
Upvotes: 0