早期函数返回宏

时间:2020-06-29 15:58:54

标签: r metaprogramming

我正在寻找类似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中的元编程,如果可能的话。

1 个答案:

答案 0 :(得分:0)

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
 
相关问题