Switch Syntax - Spicery/Nutmeg GitHub Wiki

Overview

switch is the first word of a conditional expression that evaluates a selector expression and then finds the first matching case using equality (==). For example:

switch f( x )  ### selector
    case 0:
        total <- total + 1
    case 1:
        total <- total * 2 + 1
    else:
        total <- 0
    endcase
endswitch

When this code is evaluated the selector f( x ) is calculated and stored in a hidden local variable. That variable is then compared with 0 and if that fails then compared with 1. If it is 0 then the total is incremented by 1, if it is 1 then total is doubled and incremented by 1, otherwise total is reset to 0.

The else: part can be omitted. However, in contrast to other languages, the effect is to throw an error. If no action is intended then an explicit else: must be included.

The general pattern is:


    switch SELECTOR
        case PATTERN:
            CONSEQUENT
        ...
        [any number of additional cases]
        ...
        else:
            CONSEQUENT
        endcase
    endswitch

EBNF Grammar

SwitchExpression ::= 
    'switch' Expression ':'?
        ( ( 'case' Expression )+ ( 'then' | ':' ) Statements )+
        ( 'else' ':'? Expression )? 
        ( 'end' | 'endcase' )
    ( 'end' | 'endswitch' )

Railroad diagram for switch expression

Behaviour

A switch expression tests an initial selector value against a series of cases, testing for equality == in each case. When a match is found, the statements guarded by that match are executed and then control transfers to the end of the switch expression. Optionally there is an else part that is executed if no match is found. However, is no else part is found then a failure to find a match causes an error.

In contrast to many programming languages, the cases can be arbitrary expressions and are tested in top-to-bottom order. If the compiler can determine a more efficient strategy than executing in sequential order that has the same effect, it is (of course) free to make that optimisation.

⚠️ **GitHub.com Fallback** ⚠️