Switch in Chapel

Switch statements express conditionals across many branches.

Here’s a basic switch.

proc main() {
    var i = 2;
    writeln("Write ", i, " as ");
    select i {
    when 1 do
        writeln("one");
    when 2 do
        writeln("two");
    when 3 do
        writeln("three");
    }

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

    select day() {
    when Day.Sat, Day.Sun do
        writeln("It's the weekend");
    otherwise
        writeln("It's a weekday");
    }

Switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

    var t = time();
    select {
    when t.hour < 12 do
        writeln("It's before noon");
    otherwise
        writeln("It's after noon");
    }

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable i will have the type corresponding to its clause.

    proc whatAmI(i) {
        select typeof(i) {
        when bool do
            writeln("I'm a bool");
        when int do
            writeln("I'm an int");
        otherwise
            writeln("Don't know type ", typeof(i));
        }
    }

    whatAmI(true);
    whatAmI(1);
    whatAmI("hey");
}

Running the code will give the following output:

$ ./switch
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string