Skip to content
Lesson 2 of 7

Step 1 of 4 · Reading · ~2 min

Learn

Backtracking and Cuts

! (the cut) is Prolog's commitment operator. Once Prolog passes a !, it cannot backtrack across it.

classify(N, positive) :- N > 0, !.
classify(N, negative) :- N < 0, !.
classify(_, zero).

When classify(5, X) runs:

  1. Try first clause: 5 > 0 succeeds, hits !, succeeds with X = positive
  2. The ! prevents backtracking — second/third clauses won't be tried

Without !, Prolog might come back later and find X = zero as a second answer (wrong!).

Cut as commitment:

  • After !, the choice points BEFORE this clause are also cut
  • Inside this clause, you commit to whatever was matched up to !

Common patterns:

Green cuts — the answers are the same with or without the !; it only stops the engine re-testing a branch that cannot succeed:

max(X, Y, X) :- X >= Y, !.
max(X, Y, Y) :- X < Y.

The two guards are already mutually exclusive, so removing the ! changes nothing but the work done.

Red cuts — the program is only correct because the cut fired:

max(X, Y, X) :- X >= Y, !.
max(_, Y, Y).          %% no guard — leans on the cut above

Shorter, and it answers correctly when you ask max(3, 5, M). But ask it to check an answer — max(3, 5, 3) — and the first clause fails before reaching the !, the second matches, and it wrongly succeeds. Red cuts break the predicate in modes you did not test.

A cut placed on a first clause that unifies rather than tests is red, not green:

member(X, [X|_]) :- !.          %% RED
member(X, [_|T]) :- member(X, T).

With X bound this is a harmless membership check. With X unbound, member(X, [1,2,3]) now yields only X = 1 — the other two solutions are gone.

\+ Goal — "not provable" / negation as failure. Implemented with cut:

bachelor(X) :- man(X), \+ married(X).

If married(X) succeeds, \+ married(X) fails. Useful, but be aware: \+ is "closed-world" — if Prolog can't prove X is married, it assumes X is single.

! in if-then-else:

( Cond -> Then ; Else )

This is sugar for cut-based branching. Cleaner than manual ! for simple conditionals.

Up nextAccumulatorsPatterns and State

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…