Matching Clauses

## 5.5 Matching Clauses

When Prolog systems look for clauses that match a given call, they use full unification of the goal with the clause head (but usually without the occur check). Sometimes it is useful or necessary to use pattern matching instead of full unification, i.e. during the matching only variables in the clause head can be bound, the call variables must not be changed. This means that the call must be an instance of the clause head.
The operator `-?->` at the beginning of the clause body specifies that one-way matching should be used instead of full unification in the clause head:

>     p(f(X)) :-
>         -?->
>         q(X).

Using the `?-` operator in the neck of the clause (instead of `:-`) is an alternative way of expressing the same, so the following is equivalent to the above:

>     p(f(X)) ?-
>         q(X).

Pattern matching can be used for several purposes:

- Generic pattern matching when looking for clauses whose heads are more general than the call.
- Decomposing attributed variables [4]. When an attributed variable occurs in the head of a matching clause, it is not unified with the call argument (which would trigger the unification handlers) but instead, the call argument is decomposed into the variable and its attribute(s):

  >     get_attr(X{A}, Attr) :-
  >         -?->
  >         A = Attr.

  This predicate can be used to return the attribute of a given attributed variable and fail if it is not one.
- Replacing other metalogical operations, e.g. var/1 test. Since a nonvariable in the head of a matching clause matches only a nonvariable, explicit variable tests and/or cuts may become obsolete.

If some argument positions of a matching clause are declared as output in a mode declaration, then they are not unified using pattern matching but normal unification, in this case then the variable is normally bound. The above example can thus be also written as

>     :- mode get_attr(?, -).
>     get_attr(X{A}, A) :-
>         -?->
>         true.

but in this case it must not be called with its second argument already instantiated.