|REBOL 3 Docs||Guide||Concepts||Functions||Datatypes||Errors|
|TOC < Back Next >||Updated: 19-Aug-2010 Edit History|
If condition is TRUE, evaluates the block.
/else - If not true, evaluate this block
The if function will evaluate the block when its first argument is true.
True is defined to be any value that is not false or none.
if 2 > 1 [print "that's true"] that's true
if all [ time > 10:20 age > 20 find users "bob" ] [print "that's true"] that's true
In addition, it can be pointed out that the block can be in a variable also:
blk: [print "that's true"] if 2 > 1 blk that's true
When the condition is true, the if function returns the value that is the result of evaluating the block. Otherwise, it returns none. This is a useful feature.
print if 2 > 1 [1 + 2] 3
print if 1 > 2 [1 + 2] none
names: ["Carl" "Brian" "Steve"] print if find names "Carl" ["Person found"] Person found
Unlike most other languages, REBOL uses functions, not commands to evaluate all expressions. Therefore, it's not desirable to use the word else if you need that behavior. Instead, use the either function:
either 2 > 1 [print "greater"] [print "not greater"] greater
either 1 > 2 [print "greater"] [print "not greater"] not greater
The above example is pretty common, but it should be noted that it can be easily refactored:
either 2 > 1 [print "greater"] [print "not greater"]
is better written as:
print either 2 > 1 ["greater"] ["not greater"]
or even better written as:
print pick ["greater" "not greater"] 2 > 1
The importance of this is that you're picking from a choice of two strings, and you're doing it here with one less block than the code above it.
all [ time > 10:20 age > 20 find users "bob" print "that's true" ]
n: 0 if 1 > 2 [n: 1] [n: 2] print n 0
The second block is ignored in this case and not evaluated.
The code should have used the either function:
n: 0 either 1 > 2 [n: 1] [n: 2] print n 2
The /Else refinement is obsolete and will be removed in future versions. Avoid it.
|TOC < Back Next >||REBOL.com - WIP Wiki||Feedback Admin|