Search code examples
switch-statementrebolrebol3

If...else if...else in REBOL


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?


Solution

  • 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.