10.4 Example III


In this example, we try to match the term

1. person(Nick, gender(male))

with the term

2. person(N,N)


It is a useful exercise for you to arrive at an answer before reading on. Take a moment to do so now.

Matching the two structures

Again, the top-level term is a structure whose functor (person) and arity (2) are both the same. (Rule 2.) So we try to match the individual arguments, from left to right.

Matching the first argument

Nick matches N because N is a free variable, and "Nick" is an atomic constant. N gets bound to the value "Nick". (Rule 3.)

Matching the second argument

However, when trying to match the next two arguments, N is already bound, to the value "Nick". Thus we try to match the atomic constant "Nick" with the structure "gender(male)". This does not succeed. Although both are structures, they have neither the same functor nor the same arity (rule 2).

The variable binding is undone

The variable binding

{N = Nick}

is undone because the match fails. Thus the result of the match is that the match fails, with no variable bindings.


Matching is a key process when Prolog tries to satisfy a goal. Matching occurs according to three rules which must be understood and remembered.


Hopefully by now you have a good understanding of how matching works. If not, we suggest you go back and read the chapter again.

Next, we have a quiz.

PrevLite: 10.3 Example II
NextLite: 10.5 Quiz: Matching

Prev: 10.3 Example II
Up: 10 Matching
Next: 10.5 Quiz: Matching