Hi!

I needed to generalize a loss function being optimized inside another
function, so I made it a function argument with a default value. It
worked without problems, but later I noticed that the inner function,
despite being defined in the function arguments, somehow closes over a
variable belonging to the outer function, which is defined later.

Example:

outside <- function(inside = function() print(secret)) {
        secret <- 'secret'
        inside()
}
outside()

I'm used to languages that have both lambdas and variable declaration
(like perl5 -Mstrict or C++11), so I was a bit surprised.

Does this work because R looks up the variable by name late enough at
runtime for the `secret` variable to exist in the parent environment of
the `inside` function? Can I rely on it? Is this considered bad style? 
Should I rewrite it (and how)?

-- 
Best regards,
Ivan

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.

Reply via email to