PreviousUpNext

10.9.2  Implicit Case Expressions in Functions

Mythryl function syntax supports implicit case expressions, allowing a function to be expressed as a sequence of pattern => expression pairs without need to write an explicit case.

Thus, the script

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

    fun from_roman string
        =
        case string
             "I"    => 1;
             "II"   => 2;
             "III"  => 3;
             "IV"   => 4;
             "V"    => 5;
             "VI"   => 6;
             "VII"  => 7;
             "VIII" => 8;
             "IX"   => 9;
             _      => raise exception DIE "Unsupported Roman number";
        esac;

    printf "from_roman III = %d\n" (from_roman "III");

    linux$ ./my-script
    from_roman III = 3

may be written more compactly as

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

    fun from_roman "I"    => 1;
        from_roman "II"   => 2;
        from_roman "III"  => 3;
        from_roman "IV"   => 4;
        from_roman "V"    => 5;
        from_roman "VI"   => 6;
        from_roman "VII"  => 7;
        from_roman "VIII" => 8;
        from_roman "IX"   => 9;
        from_roman _      => raise exception DIE "Unsupported Roman number";
    end;

    printf "from_roman III = %d\n" (from_roman "III");

    linux$ ./my-script
    from_roman III = 3

This facility is particularly useful when writing short recursive functions with separate terminal and recursion cases:

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

    r = [ 1, 2, 3 ];

    fun sum_list ([],       sum) => sum;
        sum_list (i ! rest, sum) => sum_list (rest, sum + i);
    end;

    printf "%d-element list summing to %d.\n" (list::length r) (sum_list (r, 0));

    linux$ ./my-script
    3-element list summing to 6.

Comments and suggestions to: bugs@mythryl.org

PreviousUpNext