[R] Scope and assignment: baffling
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Apr 1 19:14:04 CEST 2010
The code you presented is very close to object oriented in the style
of the proto package. For example,
library(proto)
# generate a single object p
p <- proto(a = 0,
geta = function(.) .$a,
incra = function(.) .$a <- .$a + 5)
p$geta()
p$a # same
p$incra()
p$geta()
# Or if you want to be able to generate objects like that:
Account <- function() proto(a = 0,
geta = function(.) .$a,
incra = function(.) .$a <- .$a + 5)
# pp is an Account object
pp <- Account()
pp$geta()
pp$a # same
pp$incra()
pp$geta()
See http://r-proto.googlecode.com for more info.
On Wed, Mar 31, 2010 at 9:44 PM, Jeff Brown <dopethatwantscash at yahoo.com> wrote:
>
> Hi,
>
> The code below creates a value, x$a, which depending on how you access it
> evaluates to its initial value, or to what it's been changed to. The last
> two lines should, I would have thought, evaluate to the same value, but they
> don't.
>
> f <- function () {
> x <- NULL;
> x$a <- 0;
> x$get.a <- function () {
> x$a;
> };
> x$increment.a <- function () {
> x$a <<- x$a + 5;
> };
> x
> };
> x <- f();
> x$increment.a();
> x$get.a();
> x$a;
>
> This can be repeated; each time you call x$increment.a(), the value
> displayed by x$get.a() changes, but x$a continues to be zero.
>
> Is that totally weird, or what?
>
> Thanks,
> Jeff
> --
> View this message in context: http://n4.nabble.com/Scope-and-assignment-baffling-tp1747582p1747582.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list