Mathematica's Which
If
Which[test_1, value_1, test_2, value_2, …]
evaluates each of thein turn, returning the value of thetest_i
corresponding to the first one that yieldsvalue_i
.True
if (test_1) value_1 else if (test_2) value_2 else ... value_n else default
if (test_1) value_1 else
if (test_2) value_2 else
...
if (test_n) value_n else
default
Which
if-else
ifelse(t_1, v_1, ifelse(t_2, v_2, ..., ifelse(t_n, v_n, default)...))
if-else
switch
switch(expr,
case_1 = value_1,
case_2 = value_2,
...
case_n = value_n,
default)
expr
case_i
Which
You can write your own function which can be used as such a control structure. The followed is based on the fact that match.call
supports lazy evaluation. (See this accepted answer):
which.val <- function(...){
clauses <- match.call(expand.dots = FALSE)$`...`
n <- length(clauses)
for(i in seq(1,n,2)){
condition = eval(clauses[[i]])
if(condition) return(clauses[[i+1]])
}
}
For testing purposes:
test <- function(a,b){
print(b)
a == b
}
The side effect can be used to see what is actually evaluated.
For example:
> x <- 3
> which.val(test(x,1),10,test(x,2),20,test(x,3),30,test(x,4),40)
[1] 1
[1] 2
[1] 3
[1] 30
Note how test(x,4)
is never evaluated.