推送返回到父函数 [英] Push return to parent function

查看:80
本文介绍了推送返回到父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以强制父函数返回输出?假设我有一个做某事"的函数,并且在每个函数的开头都想检查某件事".如果检查失败,我想返回其他".

Is there a way how to force parent function to return an output? Say I have a function that 'does something' and at the beginning of each function a want to 'check something'. If the check fails I want to return 'something else'.

在下面的示例中,做某事"是对数,检查某事"表示检查该变量是否为负数,而其他某事"为负无穷大.

In my example below 'does something' is logarithm, 'check something' means checking that the variable is nonnegative and 'something else' is minus infinity.

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.

One solution is to return 'something else' from the check function if the checks find a problem and NULL otherwise. Then I can write one if in the parent function and it's done.

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()中,但是有办法在其中包含所有功能吗?

This solution still keeps most of the functionality in separated function check() but is there a way to have all the functionality in it?

在实际问题中,检查功能不仅可以进行一次比较,而且还可以用于多种功能,因此有必要单独进行比较.同样,返回check函数的其他"取决于输入失败的条件.

In the real problem the checking function does more than just one comparison and it is used in multiple functions so it is necessary to have it separately. Also 'something else' that returns the check function depends on condition which the input fails.

更实际的示例:

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
  }
}

推荐答案

亲吻:

weird_log <- function(x) {
  if (check(x)) return(-Inf)
  log(x)
}

check <- function(x) {
  x <= 0
}

weird_log(10)  # 2.302585
weird_log(-10) # -Inf

更常见的是在检查失败时要抛出错误的用例:

More common is the use case where you want to throw an error when check fails:

weird_log <- function(x) {
  check(x)
  log(x)
}

check <- function(x) {
  if(x <= 0) stop("x <= 0", call. = FALSE)
}

weird_log(10)  # 2.302585
weird_log(-10) # Error: x <= 0

这篇关于推送返回到父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆