[R] inverse currying
baptiste auguie
baptiste.auguie at googlemail.com
Fri Oct 2 14:58:19 CEST 2009
After some more digging (grep "alist" R-devel/ ), I've come up with this,
tools:::as.alist.symbol("x")
sugar = function(fun, id = "id"){
ff <- formals(fun)
if( id %in% names(ff))
stop(paste(id, "is part of args(fun)"))
new.arg <- tools:::as.alist.symbol(id)
formals(fun) <- c(unlist(ff), new.arg)
fun
}
foo = function(x, a=1){
x
}
sugar(foo)
sugar(foo, 'a')
sugar(sugar(foo))
sugar(foo, 'my.new.arg')
Best,
baptiste
2009/10/1 baptiste auguie <baptiste.auguie at googlemail.com>:
> Dear list,
>
> I have the following function,
>
> sugar = function(fun, id = "id"){
> ff <- formals(fun)
> if( id %in% names(ff))
> stop("id is part of args(fun)")
> formals(fun) <- c(unlist(ff), alist(id=))
> fun
> }
>
> which one may use on a function foo,
>
> foo = function(x){
> x
> }
>
> sugar(foo) # results in the extended closure,
>
> function (x, id)
> {
> x
> }
>
> Its limitation (other than not working with .Primitives) is the 'id'
> tag that I add in the formals of fun(). I don't know how to create a
> alist(id=) pairlist where id can be changed. I tried the usual bquote
> and substitute approach but they don't seem to work here. I suppose I
> could do something like,
>
> parse(text = paste("alist(",id, "=)", sep=""))
>
> but this is usually not recommended.
>
> Any ideas?
>
> Best regards,
>
> baptiste
>
More information about the R-help
mailing list