Описание тега prolog-cut

Cut, spelled as an exclamation mark "!", is a special goal that serves as a control construct in the Prolog programming language.

The cut goal, written as ! in Prolog, is the main control operator. It always succeeds, and as a side effect prevents the current goal from backtracking before it.

left(a).
left(b).
right(x).
right(y).

no_cut(I,J)   :- left(I),    right(J).
with_cut(I,J) :- left(I), !, right(J).

With this setup, no_cut(I,J) succeeds normally for all (a/b, x/y) pairs.
with_cut(I,J) will only succeed for pairs with a: left will first succeed with a, the cut will succeed, and right will succeed with x. Then backtracking will have right succeed with y as well.

Without a cut, backtracking would retry left. But the cut pruned that part of the tree, so the search is over.

A cut doesn't affect the parent predicate's tree:

inner_cut(I,J) :- left(I), with_cut(I,J).

inner_cut is equivalent to no_cut.

Cuts can be used to improve efficiency when the programmer knows in advance that a clause can't succeed if another did. Such cuts are called green cuts:

green_cut(X): predicate1(X), !.
green_cut(X): predicate2(X), predicate3(X), ..., \+ predicate1(X).

Cuts that do change the outcome are called red cuts.