In chapter 1 we showed how variables can be given values through assignment statements and by calling procedures with arguments. Another way is to use pattern matching. We have already introduced the main ideas of pattern matching in section 2.3.1, where we conveniently used POP-11 notation for patterns. To do pattern matching in POP-11, we use the matches operator. In chapter 1, the familiar arithmetic operators were introduced, and matches is similar to these except that instead of working with numbers it works with lists, and instead of producing a number as a result it produces a boolean. A boolean is a data object that has only two possible values, corresponding to logical truth and falsity. We shall write these as <true> and <false> since that is how they are displayed by the print command. The result of the matches operation is <true> if the list matches the pattern, and <false> otherwise. (An apostrophe inside a POP-11 list has a special meaning -- it signifies the start of a `string' data item -- so we have used `would not' rather than the `wouldn't' of earlier examples.)
[i think i am unique in some ways] matches
[== i am ==] =>
**
<true>[then you would not be talking to me] matches
[== talking with ==] =>
**
<false>
We can also include variables in the wild cards. Note that the matches operator still returns <true> or <false> as the match can still succeed or fail, but the operation also has the side-effect of assigning the matched items to the variable. We have to declare the variables first.
vars x, y;
[eliza is a very simple program] matches
[??x is ??y] =>
**
<true>
The match was successful. Now let us look at the side effects:
x =>
**
[eliza]
y =>
**
[a very simple program]
Finally, we shall use the double up-arrow notation to build a new sentence:
[suppose^^
x were not^^
y] =>
**
[suppose eliza were not a very simple program]
Note that the double up-arrow did not just put the values of x and y into the new list; that would have produced the result
[suppose [eliza] were not [a very simple program]]
Instead, the words from the two lists were extracted and then built into the new list that was printed out. Instead of being printed out, the new list could have been stored in memory (by using the assignment arrow to assign it to a variable).