UpNext

10.8.1  Case Expression

At its simplest, the Mythryl case expression may be used much like the C switch statement:

    linux$ cat my-script
    #!/usr/bin/mythryl

    i = 3;

    case i
        1 => print "One.\n";
        2 => print "Two.\n";
        3 => print "Three.\n";
        _ => print "Dunno.\n";
    esac;

    linux$ ./my-script
    Three.

Here the underbar pattern serves as an “other” case, catching any value not handled by any of the preceding cases.

One difference is that the Mythryl case expression, unlike the C switch statement, may be evaluated to yield a value:

    linux$ cat my-script
    #!/usr/bin/mythryl

    text = "three";

    i = case text
            "one"   => 1;
            "two"   => 2;
            "three" => 3;
            _       => raise exception DIE "Unsupported case";
        esac;

    printf "Result: %d\n" i;

    linux$ ./my-script
    Result: 3

A more important difference is that the Mythryl case statement performs pattern matching. The expression given is conceptually matched against the patterns of its case clauses one by one, top to bottom, until one matches, at which point the corresponding expression is evaluated.

(The top-to-bottom scan is purely conceptual; in practice the compiler generates highly optimized code to find select the appropriate case to evaluate.)

In the succeeding sections we will enumerate the different types of patterns supported.


Comments and suggestions to: bugs@mythryl.org

UpNext