Skip to content
Prev 59292 / 398502 Next

Lexical Scoping: eval(expr,envir=)

Hi again,

In a sense, I have answered myself my question.
The functional paradigm is very well described in the article
"lexical scope and Statistical computing" by Ross Ihaka and Robert Gentleman.
And I did have read it several times...


Solution is function closure. And following code will work as I want.
Except i dont understand the help page on "eval".
What about the ability to pass a list for the value of environment()? Can I 
have an example of such a use?


My (now working) code:

---

 > ### First version: function closure
 >
 >   myObject1 =function(){
+     # Function Closure
+     function(){
+       a=1
+       list(foo=function(b=3)
+       {
+       cat("b:",b)
+       cat("\na:", a)
+       }
+        )
+       }
+   }
 >
 >   (tmp=myObject())
function(){
       a=1
       list(
       foo=function(b=3)    {
         cat("b:",b)
         cat("\na:", a)
         },
        set.a=function(newval) a <<-newval
        )
       }
<environment: 012B2CAC>
 >   tmp()$foo()
b: 3
a: 1>   tmp()$foo(b=32)
b: 32
a: 1>
 > ### Second version: add a function that allows to change the property a
 >     myObject2 =function(){
+     function(){
+       a=1
+       return(list(
+       foo=function(b=3)    {
+         cat("b:",b)
+         cat("\na:", a)
+         },
+        set.a=function(newval) a <<-newval
+        ))
+       }
+   }
 >
 >    (tmp=myObject2()())
$foo
function(b=3)    {
         cat("b:",b)
         cat("\na:", a)
         }
<environment: 012BBF08>

$set.a
function(newval) a <<-newval
<environment: 012BBF08>

 >   tmp$foo(b=32)
b: 32
a: 1>   tmp$set.a(10)
 >   tmp$foo(b=32)
b: 32
a: 10>

---

This achieves exactly the object-oriented aspect I wanted to have. And in 
fact myObject()() acts as a new instantiation of my object.

Best wishes,

Eric
At 12:05 18/11/2004, Eric Lecoutre wrote: