[R] Lexical Scoping: eval(expr,envir=)

Duncan Murdoch
Thu, 18 Nov 2004 14:12:19 -0000

On Thu, 18 Nov 2004 12:05:34 +0100, Eric Lecoutre
<lecoutre at stat.ucl.ac.be> wrote :

>
>Hi R-listers,
>
>I am trying to better undertand what we would call "functional
paradigm"
>use of S/R to better map my programming activities in other languages.
>
>This little function is aimed to create an object (at the end end, it would
>have it's own class):
>
>--
>   myObject =function(){
>     list(
>       a=1,
>       foo=function(b)
>       {
>       cat("b:",b)
>       cat("\na:", a)
>       }
>     )
>   }
>--
>To my minds, "a" would be a property of the object and
"foo" one of it's
>method.

To work with lexical scoping, you could do it as

 myObject  <- function(){
    a <- 1
     list(
       a=function() a,
       "a<-" = function(x, value) a <<- value,
       foo=function(b)
       {
       cat("b:",b,"\n")
       cat("a:", a,"\n")
       }
     )
   }

Then you can access the a property pretty easily, but changing it is
really ugly:

> m <- myObject()
> m$a()
[1] 1
> m$foo()
Error in cat("b:", b, "\n") : Argument "b" is
missing, with no default
> m$foo(1)
b: 1
a: 1
> (m$"a<-")(m, 4)
> m$foo(1)
b: 1
a: 4

It would be slightly nicer (but still ugly) if this worked:

> (m$a)(m) <- 4
Error: invalid function in complex assignment

but it doesn't.

Duncan Murdoch