Reputation: 287
In Hadley Wickham's Advanced R, I'm having some trouble understanding one of the lazy evaluation examples.
Copied from the book, chapter on functions:
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) {
}
As I understand the example, if R was not using lazy evaluation, the !is.null()
and > 0
functions would be evaluated simultaneously, throwing an error since NULL is not a permissible argument to the ">" function. Is this correct? Is it thus generally advisable to include !is.null()
in R statements when we expect that a variable could be NULL?
Upvotes: 1
Views: 316
Reputation: 7839
This is just the way the &&
operator works. It's called short-circuiting and is separate from lazy evaluation.
Lazy evaluation refers to the way function arguments are evaluated. In particular arguments are only evaluated when (if) they are actually used in the function. For example, consider the following function
f <- function(a, b) NULL
that does nothing and returns NULL
. The arguments a
and b
are never evaluated because they are unused. They don't appear in the body of f
, so you can call f
with any expressions you want (as long as it's syntactically correct) as arguments because the expressions won't be evaluated. E.g.
> f(1, 2)
NULL
> f(43$foo, unboundvariableblablabla)
NULL
Without lazy evaluation the arguments are evaluated first and then passed to the function, so the call above would fail because if you try to evaluate 43$foo
you'll get an error
> 43$foo
Error in 43$foo : $ operator is invalid for atomic vectors
Upvotes: 1