首页 > 解决方案 > 带有宏的早期函数返回

问题描述

我正在寻找类似的东西,stopifnot但它会跳出一帧而不是停止所有执行。

# like stopifnot but forces results to be zero
# using fictional "magic_eval" to promote return to the calling function
return0ifnot <- defmacro(bool) if(!bool) magic_eval("return(0)")

f <- function(x) {
 return0ifnot(x>0)
 x<-x+1
} 

f(-1) == 0
f( 1) == 2

这可以很容易地完成,ifelse(x<0,0,x+1)但我很好奇 R 中的元编程以及这是否可能。

标签: rmetaprogramming

解决方案


tryCatch提供了一种机制来stopifnot转换为所需的函数中断,但没有得到元编程解决方案。

tc_wrap <- function(f, default) function(...) tryCatch(f(...), error=function(e) default)
f_orig <- function(x) {
 stopifnot(x>0)
 x+1
}
f<-tc_wrap(f_orig, 0)

f(-1) == 0
f( 1) == 2
 

推荐阅读