From p.dalgaard@biostat.ku.dk  Tue Jun 15 22:28:14 1999
From: p.dalgaard@biostat.ku.dk (Peter Dalgaard BSA)
Date: 15 Jun 1999 23:28:14 +0200
Subject: Accessing a function's environment
In-Reply-To: Douglas Bates's message of "15 Jun 1999 13:35:39 -0500"
References: <6rpv2xs45g.fsf@verdi.stat.wisc.edu>
Message-ID: <x2yahlqhld.fsf@blueberry.kubism.ku.dk>

Douglas Bates <bates@stat.wisc.edu> writes:

>  > Fact <- mkFact()
>  > Fact         # the actual factorial function with an environment
>  function (n) 
>  {
>      nm <- paste(".", n, sep = "/")
>      if (n <= 0) 
> 	 return(1)
>      if (exists(nm, envir = .env)) 
> 	 return(get(nm, envir = .env))
>      ans <- n * Recall(n - 1)
>      assign(nm, ans, envir = .env)
>      ans
>  }
>  <environment: 0x406136e0>
>  > Fact(4)
>  [1] 24
>  > objects(env = environment(Fact), all = TRUE)
>  [1] "./1"  "./2"  "./3"  "./4"  ".env"
>  > Fact(6)
>  [1] 720
>  > objects(env = environment(Fact), all = TRUE)
>  [1] "./1"  "./2"  "./3"  "./4"  "./5"  "./6"  ".env"
> 
> If you use debug(Fact) and check what happens when Fact(6) is
> evaluated, you will see that by the time it evaluates Fact(4), it
> picks up the result from the environment.

Or (0.65 only):

> Fact<-local({
+   .env<-environment()
+   f<-function(n){     
+     nm <- paste(".", n, sep = "/")
+     if (n <= 0)
+       return(1)
+     if (exists(nm, envir = .env))
+       return(get(nm, envir = .env))
+     ans<-n*f(n-1)
+     assign(nm,ans,envir=.env)
+     ans
+   }
+ })
> Fact(6)
[1] 720
> objects(env = environment(Fact), all = TRUE)
[1] "./1"  "./2"  "./3"  "./4"  "./5"  "./6"  ".env" "f"   


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel 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-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._


Accessing a function's environment
Peter Dalgaard BSA