Skip to content
Prev 316845 / 398506 Next

Modifying a function programmatically

Dear Gabor,

Thanks for pointing me to this; didn't know the Curry function. 

For what it is worth, the two approaches perform somewhat differently in terms of computing time (my "specialize" function is given at the end):

library(functional)
## EXAMPLE 1
 ff  <- function(a,b=2,c=4){a+b+c}
 ff1 <- specialize(ff, vals=list(a=1,bb=123))
 ff2 <- Curry(ff, a = 1)
 rbenchmark::benchmark(ff1(b=10), ff2(b=10), replications=100000)
         test replications elapsed relative user.self sys.self user.child sys.child
1 ff1(b = 10)       100000    0.39    1.000      0.39        0         NA        NA
2 ff2(b = 10)       100000    0.81    2.077      0.79        0         NA        NA
 
## EXAMPLE 2
 gg <- rnorm
 gg1 <- specialize(gg, list(n=10))
 gg2 <- Curry(gg, n=1000)
 rbenchmark::benchmark(gg1(), gg2(), replications=100000)
   test replications elapsed relative user.self sys.self user.child sys.child
1 gg1()       100000    0.53    1.000      0.53     0.00         NA        NA
2 gg2()       100000    9.25   17.453      9.22     0.01         NA        NA 

where

specialize <- function(ff, vals){
	expr1 <- as.expression(body(ff))
	expr2 <- do.call("substitute", list(expr1[[1]], vals))
	gg  <- formals(ff)
	idx <-match(names(vals), names(gg))
	idx <- idx[!is.na(idx)]
	if (length(idx)>0){	gg  <- gg[-idx]}
	as.function(c(gg, expr2))
}

Best regards
S?ren










-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: 4. februar 2013 17:31
To: S?ren H?jsgaard
Cc: r-help at r-project.org
Subject: Re: [R] Modifying a function programmatically
On Mon, Feb 4, 2013 at 5:00 AM, S?ren H?jsgaard <sorenh at math.aau.dk> wrote:
This a currying operation. Try:

library(functional)
ff1 <- Curry(ff, a = 1)

# test
identical(ff1(2, 4), ff(1, 2, 4)) # TRUE

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com