Programming Languages

Author: Samuel N. Kamin
5.0
This Month Stack Overflow 1

Comments

by anonymous   2019-01-13

Reading Samuel Kamin's book on chapter 8, prolog, I found this solution that also fits here and explains how to use the cut:

The cut is a way of giving the programmer additional control over the computation by allowing him to indicate places where backtracking is impermissible. Specifically, the cut is written as an exclamation mark (!) occurring as a goal in the right-hand side of a clause such as:

G :- H, !, R.

Suppose this clause is chosen to satisfy a goal g with which G unifies. An attempt is made to satisfy H. If successful, R is proven. If the proof of R succeeds, then g is proven; in this case, the cut has no part to play. If, however, the proof of R fails, rather than backtrack and try to re-prove H, the presence of the cut causes the goal g to fail immediately; this occurs even if there are further clauses that might apply to g. An example is the definition of not-equals:

equals(X, X).
not-equals(X, Y) :- equals(X, Y), !, fail.
not-equals(X, Y).

not-equals(X, Y) should succeed if X is not equal to Y, and fail if it is; X and Y should be bound to ground expressions (i.e. have no free variables) when attempting to satisfy this goal.