Skip to content

Instantly share code, notes, and snippets.

@JonasMoss
Created Jul 12, 2019
Embed
What would you like to do?
Define functions inside enclosing environment.
#' Hide non-function variables from function.
#'
#' @param ... Named functions and function definitions.
#' @return Nothing.
H = function(...) {
function_names = names(as.list(substitute((...)))[-1])
function_defs = list(...)
envir = parent.env(parent.frame())
for(i in 1:length(function_names)) {
environment(function_defs[[i]]) = envir
assign(x = function_names[[i]],
value = function_defs[[i]],
envir = envir)
}
}
a = 5
H(adder = function(x) x + 2 + a)
adder(0)
# Error in adder(0) : object 'a' not found
H(fun1 = function(x) x + 2,
fun2 = function(x) fun1(x) + 1)
fun2(4)
# [1] 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment