Skip to content
The Cut
step 1/4

Reading — step 1 of 4

Learn

~1 min readBacktracking 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 — don't change the logic, just remove redundant work:

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

Red cuts — change the logic (you'd get wrong answers without them). Avoid when possible — they make the code harder to reason about.

\+ 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.

Discussion

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

Sign in to post a comment or reply.

Loading…