Example

CASE

Author: Marco
Return to REBOL Cookbook

Here is a simple function similar to the SWITCH function but a little more powerful in some situations. The major difference is that SWITCH selects and executes the block corresponding to a value, whereas CASE selects the block to execute corresponding to the first condition that is evaluated to true (not none).

A sample is better than a long explanation:


    x: 1 y: 2
    case/default [
        x > y [print [x "is greater than" y]]
        x = y [print [x "is equal to" y]]
        x < y [print [x "is less than" y]]
    ][
        print "no true condition"
    ]

This could be done with a set of EITHERs, but the CASE function is much simpler. Here is what the above example would require using EITHER:


    x: 1 y: 2
    either x > y [
         print [x "is greater than" y]
    ][
        either x = y [
            print [x "is equal to" y]
        ][
            either x < y [
                print [x "is less than" y]
            ][
                print "no true condition"
            ]
        ]
    ]

The code to create the CASE function is very simple:


    case: func [  
        "Find a condition and evaluates what follows it."  
        [throw]  
        cases [block!] "Block of cases to evaluate."  
        /default  
            case "Default case if no others are found."  
        /local condition body  
    ][  
        while [not empty? cases][  
            set [condition cases] do/next cases  
            if condition [  
                body: first cases  
                break  
            ]  
            cases: next cases  
        ]  
        if not body [body: any [case]]  
        do body  
    ]

2006 REBOL Technologies REBOL.com REBOL.net