PreviousUpNext

10.8.6  List Patterns

List patterns are written using syntax essentially identical to those of list expressions. Lists may be matched in their entirety using notation like [ a, b, c ]:

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

    r = [ 1, 2, 3 ];    # List expression.

    case r
        [ a, b, c ] => printf "Three-element list summing to %d.\n" (a+b+c);
        [ a, b ]    => printf "Two-element list summing to %d.\n" (a+b);
        [ a ]       => printf "One-element list summing to %d.\n" a;
        []          => printf "Zero-element list summing to 0.\n";
        _           => printf "Unsupported list length.\n";
    esac;

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

More typically, lists are pattern-matched into head-tail pairs head ! tail and processed recursively:

    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.

List patterns and other patterns may be nested arbitrarily:

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

    r = [ (1,2), (3,4), (5,6) ];

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

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

    linux$ ./my-script
    3-pair list summing to 21.

Comments and suggestions to: bugs@mythryl.org

PreviousUpNext