如何绑定函数参数
如何将参数部分绑定/应用到 R 中的函数?
这就是我走了多远,然后我意识到这种方法行不通......
bind <- function(fun,...)
{
argNames <- names(formals(fun))
bindedArgs <- list(...)
bindedNames <- names(bindedArgs)
function(argNames[!argNames %in% bindedArgs])
{
#TODO
}
}
谢谢!
How do I partially bind/apply arguments to a function in R?
This is how far I got, then I realized that this approach doesn't work...
bind <- function(fun,...)
{
argNames <- names(formals(fun))
bindedArgs <- list(...)
bindedNames <- names(bindedArgs)
function(argNames[!argNames %in% bindedArgs])
{
#TODO
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是 Curry 的一个版本,它既保留了函数参数的惰性求值,又构造了一个打印效果较好的函数:
它基本上通过生成一个匿名函数来工作,其方式与您自己构造部分绑定时的方式完全相同。
Here's a version of Curry that both preserves lazy evaluation of function argument, but constructs a function that prints moderately nicely:
It basically works by generating an anonymous function in exactly the same way you would if you were constructing the partial binding yourself.
实际上,这似乎可以作为解决方法
但是,理想情况下,我希望绑定参数从新函数中完全消失,以便可以通过名称规范调用新函数,例如使用
add <- function(a ,b) a+b
我希望(bind(add,a=2))(1)
返回 3。Actually, this seems to work as a work around
However, ideally I want the bound arguments to disappear completely from the new function so that calls to the new function can happen with name specification, e.g. with
add <- function(a,b) a+b
I would like(bind(add,a=2))(1)
to return 3.您是否尝试过查看 roxygen 的 Curry 函数?
用法示例:
编辑:
Curry 被简洁地定义为接受命名或未命名参数,但是通过
formal()
赋值将fun
部分应用到参数需要更复杂的匹配来模拟相同的功能。例如:由于此函数中的第一个参数仍然是
a
,因此您需要指定2
用于 (b=
) 的参数,或将其作为第二个参数传递。Have you tried looking at roxygen's Curry function?
Example usage:
Edit:
Curry is concisely defined to accept named or unnamed arguments, but partial application of
fun
to arguments by way offormal()
assignment requires more sophisticated matching to emulate the same functionality. For instance:Because the first argument in this function is still
a
, you need to specify which argument2
is intended for (b=
), or pass it as the second argument.