A modular implementation of pattern matching on arbitrary objects.

A pattern can be matched against a given object, resulting in zero or more successful matches. As a side effect of a successful match, pattern variables may be bound. They retain their bound values until the next matching attempt. The value of variables is unspecified before a match has been attempted. Which variables are bound by a successful match is specific to the class and structure of the pattern.

The first successful match is retrieved using the Pattern.match(A) method. All subsequent matches on the same object are retrieved using the Pattern.matchAgain() method. Any call to these methods invalidates the variables bound by previous calls. Patterns may be reused arbitrarily. Behaviour is unspecified if usage times overlap, either concurrently or recursively.

A class of patterns that yield multiple successful matches for an object may either guarantee a certain order in which the matches are produced, or leave the order unspecified. A pattern class is ordered if such an order exists for all matched objects, otherwise unordered.

A class of patterns may also guarantee that there is at most one successful match for any object. A pattern class is deterministic if there is at most one match, otherwise nondeterministic. Nondeterministic patterns typically require internal memory to keep track of subsequent matches. That memory can be discarded explicitly, forfeiting remaining matches for the same object, and potentially allowing some heap space to be reclaimed.