如何绑定函数参数

Coo*_*kie 4 bind r apply

如何将参数部分绑定/应用于R中的函数?

这是我有多远,然后我意识到这种方法不起作用......

bind <- function(fun,...)
{
  argNames <- names(formals(fun))
  bindedArgs <- list(...)
  bindedNames <- names(bindedArgs)
  function(argNames[!argNames %in% bindedArgs])
   {
   #TODO
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

had*_*ley 8

这是Curry的一个版本,它既保留了函数参数的惰性求值,又构造了一个适度打印的函数:

Curry <- function(FUN, ...) {
  args <- match.call(expand.dots = FALSE)$...
  args$... <- as.name("...")

  env <- new.env(parent = parent.frame())

  if (is.name(FUN)) {
    fname <- FUN
  } else if (is.character(FUN)) {
    fname <- as.name(FUN)
  } else if (is.function(FUN)){
    fname <- as.name("FUN")
    env$FUN <- FUN
  } else {
    stop("FUN not function or name of function")
  }
  curry_call <- as.call(c(list(fname), args))

  f <- eval(call("function", as.pairlist(alist(... = )), curry_call))
  environment(f) <- env
  f
}
Run Code Online (Sandbox Code Playgroud)

它基本上是通过生成一个匿名函数来完成的,就像你自己构建部分绑定一样.


Coo*_*kie 5

实际上,这似乎可以解决

bind <- function(fun,...)
{
  boundArgs <- list(...)
  formals(fun)[names(boundArgs)] <- boundArgs
  fun
}
Run Code Online (Sandbox Code Playgroud)

但是,理想情况下,我希望绑定的参数从新函数中完全消失,以便对新函数的调用可以通过名称说明进行,例如,add <- function(a,b) a+b我想(bind(add,a=2))(1)返回3。