Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No-op function as conditional replacement for stopifnot()

Tags:

function

r

Is there a no-op function in R so that, even if the parameters would be expensive to evaluate, it returns immediately? I'm looking for a conditional replacement of the stopifnot function.

> noop(runif(1e20))
# returns immediately and uses no memory
like image 544
krlmlr Avatar asked Jun 07 '12 14:06

krlmlr


1 Answers

I think this would do:

noop <- function(...) invisible(NULL)

as lazy evaluation comes to the rescue here:

R> system.time(replicate(1e4, noop(runif(1e2))))
   user  system elapsed 
   0.01    0.00    0.01 
R> system.time(replicate(1e4, noop(runif(1e5))))
   user  system elapsed 
   0.01    0.00    0.02 
R> system.time(replicate(1e4, noop(runif(1e8))))
   user  system elapsed 
   0.01    0.00    0.01 
R> system.time(replicate(1e4, noop(runif(1e11))))
   user  system elapsed 
   0.01    0.00    0.01 
R> 

so even when we increase N no runtime increase can be seen.

like image 60
Dirk Eddelbuettel Avatar answered Sep 19 '22 13:09

Dirk Eddelbuettel