Course contentsShow
← Computer Science
Lesson 2163 of 2,87248. Programming ParadigmsFree lesson

The Cut Operator (!)

Controlling backtracking explicitly with the cut operator to prune search trees and commit to choices.

The Cut Operator (!)

You'll learn how to use Prolog's cut operator to stop backtracking and commit to decisions, making your logic programs more efficient and predictable.

What is the Cut?

In Prolog, the cut operator (written as !) is a special goal that always succeeds but has a critical side effect: it prunes the search tree. Once Prolog executes a cut, it commits to all choices made up to that point in the current rule. It cannot backtrack past the cut to try alternative clauses or bindings.

Think of it like crossing a one-way door in a maze: once you pass through, you can't go back to explore other paths you skipped earlier.

How It Works

Without cut, Prolog explores every possible solution through backtracking. The cut tells Prolog: "Stop searching for alternatives here—this is the right path."

When placed in a rule body:

  • All choice points before the cut in that rule are removed
  • Prolog will not try alternative clauses for that predicate
  • Backtracking can still happen after the cut within the same clause

Why Use Cut?

Efficiency: Prevents wasted computation by eliminating useless branches of the search tree.

Control: Forces deterministic behavior when you know only one solution matters.

Commitment: Implements "if-then-else" logic—once a condition matches, commit to that path.

Example Pattern

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

The cut here says: "If X ≥ Y, return X and don't try the second clause." Without it, Prolog might backtrack and incorrectly try the second rule.

Key Takeaway: The cut operator (!) prevents backtracking past its position, pruning the search space to commit to choices and improve both performance and logical clarity.