Home > Software design >  What is the Most Rly Way for Lazy Conditional Evaluation
What is the Most Rly Way for Lazy Conditional Evaluation

Time:06-01

The case. I have a part of code like this: if (exists("mybooleanvar") & mybooleanvar) {statement1} else {statement2}. I expect that if the conditions are lazily (short-circuit) evaluated astatement1 will be run if mybooleanvar is not assigned and statement2 will be called if mybooleanvar does not exist or equals FALSE. But in practice I am getting a runtime error showing that the value of mybooleanvar is acessed and compared to TRUE if exists("mybooleanvar") == FALSE. So the complete boolean evaluation takes place.

Of course the issue can be solved by enclosed if statements with outer ones evaluating exists() and inner ones - booleans. But I wonder what is the most Rly way to properly avoid evaluation of n'th members of conditional statement if the result becomes known despite the values of further statements. For example statement1 & statement2 will be FALSE if statement1 == FALSE. statement1 | statement2 is TRUE if statement1 == TRUE and statement2 needs not to be checked (or at least this check can be switched off by something like compiler directive {$B-) in Delphi).

CodePudding user response:

Here I would use && instead of &. They differ in two ways (cf. ?"&&"):

The shorter form performs elementwise comparisons ...

and:

The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

Example:

foo <- function()
  if (exists("x") && (x)) cat("is TRUE\n") else cat("not existing or FALSE\n")

x <- TRUE
foo()

x <- FALSE
foo()

rm(x)
foo()

More can be found in this post.

  • Related