有没有办法强制父函数返回输出?假设我有一个“做某事”的函数,并且在每个函数的开头想要“检查某事”。如果检查失败我想返回“其他东西”。
在我下面的示例中,“做某事”是对数,“检查某事”意味着检查变量是否为非负数,“其他事情”是否为负无穷大。
weird_log <- function(x) {
check(x)
log(x)
}
check <- function(x) {
if (x <= 0)
eval.parent(parse(text = 'return(-Inf)'))
}
这个例子不起作用
weird_log(10) # 2.302585
weird_log(-10) # NaN
一种解决方案是,如果检查发现问题,则从检查函数返回“其他内容”,并且NULL
否则。那我可以写一篇if
在父函数中就完成了。
weird_log <- function(x) {
y <- check(x)
if (!is.null(y)) return(y)
log(x)
}
check <- function(x) {
if (x <= 0) {
-Inf
} else {
NULL
}
}
该解决方案仍然将大部分功能保留在分离的功能中check()
但有没有办法拥有其中的所有功能呢?
在实际问题中,检查函数不仅仅进行一次比较,而且它在多个函数中使用,因此有必要单独使用它。还有返回的“其他东西”check
功能取决于输入失败的条件。
更现实的例子:
weird_log <- function(input) {
y <- check(input)
if (!is.null(y)) return(y)
list(log = log(input$x))
}
check <- function(input) {
if (is.null(input$x)) {
list(error = 'x is missing')
} else if (!is.numeric(input$x)) {
list(error = 'x is not numeric')
} else if (x <= 0) {
list(log = -Inf, warn = 'x is not positive')
} else {
NULL
}
}