What Is a Match?

In the previous sections of this chapter, we've talked about Prolog "matching answers to questions", "finding a match", "matching conditions with facts", "matching variables with constants", and so on. In this section we explain what we mean when we use the term "match."

There are several ways Prolog can match one thing to another. Obviously, identical structures match each other;

    parent(joe,tammy) matches parent(joe,tammy).

However, a match usually involves one or more free variables. For example, with X free,

    parent(joe,X) matches parent(joe,tammy)

and X takes on (is bound to) the value tammy.

If X is already bound, it acts exactly like a constant. Thus, if X is bound to the value tammy, then

    parent(joe,X) matches parent(joe,tammy) but
    parent(joe,X)
would not match parent(joe,millie)

The second instance doesn't match because, once a variable becomes bound, its value can't change.

How could a variable, bindings already be bound when Prolog tries to match it with something? Remember that variables don't store values--they only stay bound for the length of time needed to find (or try to find) one solution to one goal. So the only way a variable could be bound before trying a match is that the goal involves more than one step, and the variable became bound in a previous step. For example,

    parent(joe,X), parent(X,jenny)

is a legitimate goal; it means, "Find someone who is a child of Joe and a parent of Jenny." Here X will already be bound when the subgoal parent(X,jenny) is reached. If there is no solution to parent(X,jenny), Prolog will unbind X and go back and try to find another solution to parent(joe,X), then see if parent(X,jenny) will work with the new value of X.

Two free variables can even match each other. For example,

    parent(joe,X) matches parent(joe,Y)

binding the variables X and Y to each other. As long as the binding lasts, X and Y are treated as a single variable, and if one of them gets a value the other one will immediately have the same value. When free variables are bound to each other like this, they're called pointers, shared free sharing variables. Some really powerful programming techniques involve binding together variables that were originally separate.

In Prolog, variable bindings (values) are passed in two ways: in and out. The direction in which a value is passed is referred to as its flow pattern. When a variable is passed into a clause, it is an input ,  argument, signified by (i); when passed out of a clause, a variable is an output argument, signified by (o).

Summary

These are the ideas we've introduced in this chapter:

A free variable matches a constant or a previously-bound variable (and becomes bound to that value).

Two free variables can match (and be bound to) each other. As long as the binding lasts, they are treated as a single variable; if one gets a value the other will immediately have the same value.