I've noticed that REBOL doesn't have a built in if...elsif...else
syntax, like this one:
theVar: 60
{This won't work}
if theVar > 60 [
print "Greater than 60!"
]
elsif theVar == 3 [
print "It's 3!"
]
elsif theVar < 3 [
print "It's less than 3!"
]
else [
print "It's something else!"
]
I have found a workaround, but it's extremely verbose:
theVar: 60
either theVar > 60 [
print "Greater than 60!"
][
either theVar == 3 [
print "It's 3!"
][
either theVar < 3 [
print "It's less than 3!"
][
print "It's something else!"
]
]
]
Is there a more concise way to implement an if...else if...else
chain in REBOL?
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to false , and the current elseif expression evaluated to true .
With the if statement, a program will execute the true code block or do nothing. With the if/else statement, the program will execute either the true code block or the false code block so something is always executed with an if/else statement.
Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The construct you would be looking for would be CASE. It takes a series of conditions and code blocks to evaluate, evaluating the blocks only if the condition is true and stopping after the first true condition is met.
theVar: 60
case [
theVar > 60 [
print "Greater than 60!"
]
theVar == 3 [
print "It's 3!"
]
theVar < 3 [
print "It's less than 3!"
]
true [
print "It's something else!"
]
]
As you see, getting a default is as simple as tacking on a TRUE condition.
Also: if you wish, you can have all of the cases run and not short circuit with CASE/ALL. That prevents case from stopping at the first true condition; it will run them all in sequence, evaluating any blocks for any true conditions.
And a further option is to use all
all [
expression1
expression2
expression3
]
and as long as each expression returns a true value, they will continue to be evaluated.
so,
if all [ .. ][
... do this if all of the above evaluate to true.
... even if not all true, we got some work done :)
]
and we also have any
if any [
expression1
expression2
expression3
][ this evaluates if any of the expressions is true ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With