Accessing slots of an S4 function superclass

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.__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"....


Resorting to a little language manipulation

setClass("Pow", representation("function", pow="numeric"),
           function(x) {
               self <- eval([[1]])
           }, 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

         representation(fun="function", param="numeric"),
           fun=function(x, param) function(x) x^param,

setGeneric("fun", function(x) standardGeneric("fun"))
setMethod(fun, "ParameterizedFunFactory",
          function(x) x@fun(x, x@param))


> f = g = new("ParameterizedFunFactory")
> g@param = 3
> fun(f)(2)
[1] 4
> fun(g)(2)
[1] 8

Need Your Help

How should I handle Chrome tabs that don't yet have a content script loaded?

javascript google-chrome-extension

I'm trying to extend some of the handling of messaging between my background process and content scripts. In the normal course of things my background process sends a message via postMessage() and ...

Get UITableView's height

iphone xcode uitableview

I have created a UITableview with custom UITableViewCell.The UITableViewCell contains UILabels and I have calculated the height of each cell based on the cells height.But how can I get the tableview

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.