[Rd] pinning down symbol values (Scoping/Promises) question
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Feb 17 02:04:05 CET 2007
See ?force
a <- function(z) {
force(k)
function() z+k
}
On 2/16/07, Ross Boylan <ross at biostat.ucsf.edu> wrote:
> I would like to define a function using symbols, but freeze the symbols
> at their current values at the time of definition. Both symbols
> referring to the global scope and symbols referring to arguments are at
> issue. Consider this (R 2.4.0):
> > k1 <- 5
> > k
> [1] 100
> > a <- function(z) function() z+k
> > a1 <- a(k1)
> > k1 <- 2
> > k <- 3
> > a1()
> [1] 5
> > k <- 10
> > k1 <- 100
> > a1()
> [1] 12
>
> First, I'm a little surprised that that the value for k1 seems to get
> pinned by the initial evaluation of a1. I expected the final value to
> be 110 because the z in z+k is a promise.
>
> Second, how do I pin the values to the ones that obtain when the
> different functions are invoked? In other words, how should a be
> defined so that a1() gets me 5+100 in the previous example?
>
> I have a partial solution (for k), but it's ugly. With k = 1 and k1 =
> 100,
> > a <- eval(substitute(function(z) function() z+x, list(x=k)))
> > k <- 20
> > a1 <- a(k1)
> > a1()
> [1] 101
> (by the way, I thought a <- eval(substitute(function(z) function() z+k))
> would work, but it didn't).
>
> This seems to pin the passed in argument as well, though it's even
> uglier:
> > a <- eval(substitute(function(z) { z; function() z+x}, list(x=k)))
> > a1 <- a(k1)
> > k1 <- 5
> > a1()
> [1] 120
>
> --
> Ross Boylan wk: (415) 514-8146
> 185 Berry St #5700 ross at biostat.ucsf.edu
> Dept of Epidemiology and Biostatistics fax: (415) 514-8150
> University of California, San Francisco
> San Francisco, CA 94107-1739 hm: (415) 550-1062
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
More information about the R-devel
mailing list