Advanced R 中带有 NULL 的惰性评估示例
Lazy evaluation example with NULL in Advanced R
在 Hadley Wickham 的 Advanced R 中,我在理解惰性求值示例之一时遇到了一些问题。
从书中复制,关于函数的章节:
Laziness is useful in if statements — the second statement below will be >evaluated only if the first is true. If it wasn’t, the statement would return >an error because NULL > 0 is a logical vector of length 0 and not a valid input >to if.
x <- NULL
if (!is.null(x) && x > 0) {
}
据我所知,如果 R 没有使用惰性求值,!is.null()
和 > 0
函数将同时求值,抛出错误,因为 NULL 不是“ >”功能。这个对吗?因此,当我们期望变量可能为 NULL 时,通常建议在 R 语句中包含 !is.null()
吗?
这正是 &&
运算符的工作方式。它称为 short-circuiting 并且与惰性求值是分开的。
惰性求值指的是函数参数的求值方式。特别是参数仅在(如果)它们实际在函数中使用时才被评估。例如,考虑以下函数
f <- function(a, b) NULL
什么都不做,returns NULL
。参数 a
和 b
永远不会被评估,因为它们未被使用。它们不会出现在 f
的正文中,因此您可以使用任何您想要的表达式(只要它在语法上是正确的)作为参数调用 f
,因为不会计算表达式。例如
> f(1, 2)
NULL
> f(43$foo, unboundvariableblablabla)
NULL
如果没有惰性求值,参数会先求值然后传递给函数,所以上面的调用会失败,因为如果你尝试求值 43$foo
你会得到一个错误
> 43$foo
Error in 43$foo : $ operator is invalid for atomic vectors
在 Hadley Wickham 的 Advanced R 中,我在理解惰性求值示例之一时遇到了一些问题。
从书中复制,关于函数的章节:
Laziness is useful in if statements — the second statement below will be >evaluated only if the first is true. If it wasn’t, the statement would return >an error because NULL > 0 is a logical vector of length 0 and not a valid input >to if.
x <- NULL
if (!is.null(x) && x > 0) {
}
据我所知,如果 R 没有使用惰性求值,!is.null()
和 > 0
函数将同时求值,抛出错误,因为 NULL 不是“ >”功能。这个对吗?因此,当我们期望变量可能为 NULL 时,通常建议在 R 语句中包含 !is.null()
吗?
这正是 &&
运算符的工作方式。它称为 short-circuiting 并且与惰性求值是分开的。
惰性求值指的是函数参数的求值方式。特别是参数仅在(如果)它们实际在函数中使用时才被评估。例如,考虑以下函数
f <- function(a, b) NULL
什么都不做,returns NULL
。参数 a
和 b
永远不会被评估,因为它们未被使用。它们不会出现在 f
的正文中,因此您可以使用任何您想要的表达式(只要它在语法上是正确的)作为参数调用 f
,因为不会计算表达式。例如
> f(1, 2)
NULL
> f(43$foo, unboundvariableblablabla)
NULL
如果没有惰性求值,参数会先求值然后传递给函数,所以上面的调用会失败,因为如果你尝试求值 43$foo
你会得到一个错误
> 43$foo
Error in 43$foo : $ operator is invalid for atomic vectors