[R] Weird feature when creating function lists with apply
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Wed Oct 10 11:36:31 CEST 2001
Uffe Høgsbro Thygesen <uht at dfu.min.dk> writes:
> # Create a function which returns a function
> > f1 <- function(a) {return(function(x) a*x)}
> # Create a list of functions, parameterised by 1:4
> > apply(as.array(1:4),1,f1)[[2]](1)
> [1] 4
>
> # Repeat
> > f2 <- function(a) {b <- a ;return(function(x) b*x)}
> > apply(as.array(1:4),1,f2)[[2]](1)
> [1] 2
This should work too:
f3 <- function(a) {a;function(x) a*x}
apply(as.array(1:4),1,f3)[[2]](1)
It is essentially the same situation that caused Luke Tierney
substantial headscratching recently. The key is lazy evaluation.
Here's part of the conversation from then:
[Snip from email from Luke]
On Wed, Aug 29, 2001 at 11:25:54PM +0200, Peter Dalgaard BSA wrote:
> Luke Tierney <luke at nokomis.stat.umn.edu> writes:
>
> > > mkf <- function(j) function() j
> > > for (i in 1:10) x[[i]] <- mkf(i)
> >
> > That doesn't work either:
> >
> > > x[[2]]()
> > [1] 10
> >
> > but for a slightly different reason: Lazy evaluation defers evaluating
> > the argument to mkf(i) until the funtction is called.
>
> Argh. I've been looking at this for ten minutes and it still refuses
> to sink in....
Now imagine getting bitten by this while experimenting with some new
threading code, which is of course then the prime suspect for all bad
things that happen, and you can see why Duncan and I were tearing our
hair out for a bit :-).
>
> Oh, now I see it:
>
> > z<-2 ; f<-mkf(z)
> > z<-3
> > f()
> [1] 3
> > z<-4
> > f()
> [1] 3
>
> The return value of mkf is not really a function of the argument, it
> is the same function every time, namely the function returning "j"
> which it will look up in its parent environment (the lexical one...)
> when called, and only *then* will it force the promise.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list