How do I emulate the Lisp let function in R?

I am trying to write a function let

that allows me to do things like:

let(a=2, b=3, a+b)
>>> 5

      

I am currently stuck with

let <- function(..., expr) {
  with(list(...), quote(expr))
}

      

which doesn't work at all. Any help was appreciated.

+3


source to share


2 answers


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 do not want to specify an expression to evaluate (i.e. pass it through expr

), and if you are sure that this will always be the last argument, you can 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

      

+11


source


let <- function(a,b, expr=a+b){return(expr)}
let(2,3)
# [1] 5

      



+1


source







All Articles