REBOL 3 Docs Guide Concepts Functions Datatypes Errors
  TOC < Back Next >   Updated: 12-Aug-2010 Edit History  

REBOL 3 Functions: either

either  condition  true-block  false-block

If condition is TRUE, evaluates the first block, else evaluates the second.



true-block [block!]

false-block [block!]

See also:

if   any   all   unless   case   switch   pick  


The either function will evaluate one block or the other depending on a condition.

This function provides the same capability as the if-else statements found in other languages. Because REBOL is a functional language, it is not desirable to use the word else within the expression.

Here's an example:

either 2 > 1 [print "greater"] [print "not greater"]
either 1 > 2 [print "greater"] [print "not greater"]
not greater

The condition can be the result of several expressions within any or and, or any other function that produces a result:

either all [
    time > 10:20
    age > 20
    find users "bob"
] [print "that's true"] [print "that's false"]
that's true

In addition, it can be pointed out that the evaluated blocks can be within a variable:

blk1: [print "that's true"]
blk2: [print "that's false"]
either 2 > 1 blk1 blk2
that's true

Return Value

The either function returns the result of the block that it evaluates.

print either 2 > 1 ["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.

Be careful with this last method. The pick function only allows true and false, not none. See either for more details.

A Common Error

A common error is to forget to provide the second block to the either function. This usually happens when you simplify an expression, and forget to change the either to an if function.

This is wrong:

either 2 > 1 [print "greater"]

and it may become quite confusing as to why your program isn't working correctly.

You should have written:

if 2 > 1 [print "greater"]

  TOC < Back Next > - WIP Wiki Feedback Admin