How do I reliably and efficiently hash a function?
Thanks. I know about `local` (and functions within functions). In fact, the functions are *already* defined inside their own environment (same as what `local` does). But unfortunately this doesn?t solve my problem, since the functions? parent environment gets changed during the function?s execution, and I need to retrieve my stored data *after* that point, inside the function. I?ve tried to create a more exact example of what?s going on ? unfortunately it?s really hard to simplify the problem without losing crucial details. Since the code is just a tad too long, I?ve posted it as a Github Gist: https://gist.github.com/klmr/53c9400e832d7fd9ea5c The function `f` in the example calls `get_meta()` twice, and gets different results before and after calling an ancillary function that modifies the function?s `parent.env`. I want it to return the same information (?original?) both times. On Fri, Dec 11, 2015 at 10:49 AM, Mark van der Loo
<mark.vanderloo at gmail.com> wrote:
In addition to what Charles wrote, you can also use 'local' if you don't want a function that creates another function.
f <- local({info <- 10; function(x) x + info})
f(3)
[1] 13 best, Mark Op vr 11 dec. 2015 om 03:27 schreef Charles C. Berry <ccberry at ucsd.edu>:
On Thu, 10 Dec 2015, Konrad Rudolph wrote:
I?ve got the following scenario: I need to store information about an R function, and retrieve it at a later point. In other programming languages I?d implement this using a dictionary with the functions as keys. In R, I?d usually use `attr(f, 'some-name')`. However, for my purposes I do not want to use `attr` because the information that I want to store is an implementation detail that should be hidden from the user of the function (and, just as importantly, it shouldn?t clutter the display when the function is printed on the console). `comment` would be almost perfect since it?s hidden from the output when printing a function ? unfortunately, the information I?m storing is not a character string (it?s in fact an environment), so I cannot use `comment`. How can this be achieved?
See https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Scope For example, these commands: foo <- function() {info <- "abc";function(x) x+1} func <- foo() find("func") func(1) ls(envir=environment(func)) get("info",environment(func)) func Yield these printed results: : [1] ".GlobalEnv" : [1] 2 : [1] "info" : [1] "abc" : function (x) : x + 1 : <environment: 0x7fbd5c86bc60> The environment of the function gets printed, but 'info' and other objects that might exist in that environment do not get printed unless you explicitly call for them. HTH, Chuck p.s. 'environment(func)$info' also works.
______________________________________________ R-devel at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel