[   ^ to index...   |   <-- previous   ]

Pattern and expression trees

Here's the informal matching algorithm I gave you last time:

fun matches(left, right) =
    if left is a constant then
        if left = right then true else false
    else if left is a variable then true
    else if left is a wildcard then true
    else if left is a compound constructor then
        if right has the same top-level constructor then
             if each component of left matches each component of right then
                 true
             else
                 false
        else
            false
    else (* left may not appear in a pattern! *)
        raise some kind of error

Consider the following data type for a very restricted subset of ML patterns and expressions:

datatype Pattern = PatInt of int
                 | PatVar of string
                 | PatWildcard
                 | PatCon of string * Pattern list;

datatype Expr = ExprInt of int
              | ExprVar of string
              | ExprCompound of string * Expr list;

Write a function match(pattern, expr) that determines whether a pattern matches an expression. Use pattern-matching style, obviously. You do not need to test for variable uniqueness in the pattern (as a real ML implementation would do).

P.S. Some other things a real implementation would have to take care of (a very nonexhaustive list):


Keunwoo Lee
Last modified: Thu Apr 19 10:51:10 PDT 2001