I'm trying to write a program that takes an expression as an input and returns a function with that expression bound as its body.
caller <- function (expr, params) {
Function <- function (params, body, env = parent.frame()) {
# returns a function
}
Function(params, body = expr)
}
func <- caller (a + b, c('a', 'b'))
func(1, 2)
[1] 3
I can bind the parameters quite easily, by using something like
params <- c('a', 'b')
f <- function() {}
formals(f) <- structure(
replicate(length(params), NULL),
names = params
)
I'm having trouble coming up with a way of dynamically adding the expression as the body. I've tried use substitute(), and adapting make_function from the pryr library, but I can't quite get things to work. My best attempt is
body(f, parent.frame()) <- as.list( match.call() )[-1]$body
I couldn't get this to work with substitute either. Any thoughts on how to bind the body in so that the topmost program works as expected?
I've seen similar questions on SO, but the solutions don't seem to satistfy this problem.