How to emulate Lisp's let function in R?

evaluation, functional-programming, r

Solution

Here's one way:

let <- function(..., expr) {
    expr <- substitute(expr)
    dots <- list(...)
    eval(expr, dots)
}

let(a = 2, b = 3, expr = a+b)
# [1] 5

Edit: Alternatively, if you don't want to have to name the expression-to-be-evaluated (i.e. passing it in via `expr`), and if you are certain that it will always be the last argument, you could do something like this.

let <- function(...) {
    args <- as.list(sys.call())[-1]
    n <- length(args)
    eval(args[[n]], args[-n])
}

let(a = 2, b = 3, a + b)
# [1] 5

Problem

I'm trying to write a `let` function that allows me to do things like: ``` let(a=2, b=3, a+b) >>> 5 ``` Currently I'm stuck with ``` let <- function(..., expr) { with(list(...), quote(expr)) } ``` which doesn't work at all. Any help appreciated.

Original source