r - 带有宏的早期函数返回
问题描述
我正在寻找类似的东西,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 中的元编程以及这是否可能。
解决方案
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
推荐阅读
- vue.js - 无法读取属性全局变量Vuejs
- r - R Shiny,找不到对象“输入”
- python - 在 IPython 中运行 ProcessPoolExecutor
- python - 使用 pyodbc 将 access 数据库连接到 python 时遇到问题-尝试读取数据
- html - 如何在 python 文本编辑器中运行 HTML 文件
- c++ - 如何在对象组合中正确使用 + 运算符?
- excel - 仅在文件打开时评估 Excel Online 中的公式一次?
- c++ - 由于 Linux 上的编译器变化,安装的库和我的代码之间存在冲突
- javascript - 我们可以在 JavaScript 的自定义函数中使用预定义函数吗?
- apache-kafka - 启用 SASL 身份验证时,Kafka 从 Zookeeper 收到 Sasl 异常