PreviousUpNext

10.8.2  Tuple Patterns

Tuple patterns are very simple. They are written using syntax essentially identical to those of tuple expressions: A comma-separated list of pattern elements wrapped in parentheses:

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

    case (1,2)
        (1,1) => print "(1,1).\n";
        (1,2) => print "(1,2).\n";
        (2,1) => print "(2,1).\n";
        (2,2) => print "(2,2).\n";
        _     => print "Dunno.\n";
    esac;

    linux$ ./my-script
    (1,2).

What makes pattern-matching really useful is that we may use variables in patterns to extract values from the input expression:

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

    case (1,2)
        (i,j) => printf "(%d,%d).\n" i j;
    esac;

    linux$ ./my-script
    (1,2).

Another useful property is that patterns may be arbitrarily nested:

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

    case (((1,2),(3,4,5)),(6,7))
        (((a,b),(c,d,e)),(f,g)) => printf "(((%d,%d),(%d,%d,%d)),(%d,%d))\n" a b c d e f g;
    esac;

    linux$ ./my-script
    (((1,2),(3,4,5)),(6,7))

Note how much more compact and readable the above code is than the equivalent code explicitly extracting the required values using the underlying #1 #2 #3 ... operators:

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

    x = (((1,2),(3,4,5)),(6,7));

    printf "(((%d,%d),(%d,%d,%d)),(%d,%d))\n"
        (#1 (#1 (#1 x)))
        (#2 (#1 (#1 x)))
        (#1 (#2 (#1 x)))
        (#2 (#2 (#1 x)))
        (#3 (#2 (#1 x)))
            (#1 (#2 x))
            (#2 (#2 x));

    linux$ ./my-script
    (((1,2),(3,4,5)),(6,7))

Using a case expression to matching a tuple of Boolean values is often shorter and clearer than writing out the equivalent set of nested if statements:

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

    bool1 = TRUE;
    bool2 = FALSE;

    case (bool1, bool2)
       (TRUE,  TRUE ) => print "Exclusive-OR is FALSE.\n";
       (TRUE,  FALSE) => print "Exclusive-OR is TRUE.\n";
       (FALSE, TRUE ) => print "Exclusive-OR is TRUE.\n";
       (FALSE, FALSE) => print "Exclusive-OR is FALSE.\n";
    esac;

    linux$ ./my-script
    Exclusive-OR is TRUE.

Compare with the nested-if alternative:

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

    bool1 = TRUE;
    bool2 = FALSE;

    if bool1
        if bool2
            print "Exclusive-OR is FALSE.\n";
        else
            print "Exclusive-OR is TRUE.\n";
        fi;
    else
        if bool2
            print "Exclusive-OR is TRUE.\n";
        else
            print "Exclusive-OR is FALSE.\n";
        fi;
    fi;

    linux$ ./my-script
    Exclusive-OR is TRUE.

The latter code is both longer and harder to understand and maintain than the former code.


Comments and suggestions to: bugs@mythryl.org

PreviousUpNext