From r.hankin at noc.soton.ac.uk  Mon Jan 14 12:59:58 2008
From: r.hankin at noc.soton.ac.uk (Robin Hankin)
Date: Mon, 14 Jan 2008 11:59:58 +0000
Subject: [Rd] as.function()
In-Reply-To: <478B4C88.6070205@stats.uwo.ca>
References: <39993FF2-8FE4-4FB9-A752-8A3ABAB18CEF@noc.soton.ac.uk>
	<478B4C88.6070205@stats.uwo.ca>
Message-ID: <1572149B-D187-451B-8A86-E5D9811A5DDB@noc.soton.ac.uk>


On 14 Jan 2008, at 11:50, Duncan Murdoch wrote:

> Robin Hankin wrote:
>> Hi
>>

[snip]

>> a <- crossprod(matrix(rnorm(12),ncol=3))
>> class(a) <- "foo"
>>
>> f <- as.function(a)       # need help to write as.function.foo()
>> x <- diag(3)
>>
>> f(x)             #should give tr(ax)
>>
>> a <- 4
>> f(x)           # should still give tr(ax) even though "a" has been   
>> reassigned.
>>
>>
> Brian's answer was what you want.  A less general version is this:
>
> > as.function.foo <- function(x, ...) {
> +    function(b) tr(x %*% b)
> + }
>


Wow.  Got it!  Looks like I'll have to read the R Language Definition  
again.

Thanks everyone.




> (I switched the names of the args, because the first arg to  
> as.function.foo should match the name of the first arg to  
> as.function).
>
> I was a little surprised that this worked even if a was changed  
> without ever evaluating f, because I thought lazy evaluation would  
> mess up that case.  But of course the value of x is forced when R  
> evaluates it to find out the class for dispatch to the method.
>
> Duncan Murdoch

--
Robin Hankin
Uncertainty Analyst and Neutral Theorist,
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



[Rd] as.function()
Robin Hankin