The MatchIn Object

The MatchIn object is designed to allow creating pattern match expressions that will generate a list of bindings for each of the parameters of an expression. Among other uses, the MatchIn object provides a way to iterate over a list.

An example will help demostrate how the MatchIn object is used:

This expression will find the first value in the list that is greater than zero, in the example the return value would be 2.

Similarly, we can write a clause that returns a list containing all of the values in the original list that are greater than zero:

The only difference between the first and second examples is that in the second example we are using AssertList instead of Assert for the outer assert. The return value in this case is a list containing 2 and 3.

Testing for properties is another common application for the MatchIn object:

in this clause, the right-hand side is only evaluted if the expression bound to the variable "a" contains the DefaultResult property in its properties list.

MatchIn can be used with expressions other than just lists. The MatchIn object treats whatever object is on the right-hand side as a list of parameters, so we could write a function named GetParameters[f] that contained the clause:

and GetParameters[a + b + c] would return List[a, b, c], GetParameters[a - b] would return List[a, b], and so on.

The MatchIn object can also be used with patterns on the left-hand side other than just a variable, for example:

in this case, each of the parameters of "f" will be matched to the pattern a/b. If the match succeeds, then the expression on the right-hand side will be generated using the bound variables from the match. If this clause is the only clause in the function MyFn3, then MyFn3[a + b/c + d +e/f] will return a list containing "c" and "f".