Skip to content
Backtracking and Choice Points
step 1/5

Reading — step 1 of 5

Learn

~1 min readBacktracking and Cuts

Prolog's engine searches for proofs by trying clauses in order. When a goal fails, the engine backtracks to the most recent choice point and tries the next alternative.

likes(ada, math).
likes(ada, engines).
likes(linus, c).

?- likes(ada, X).
X = math ;            %% first answer
X = engines ;          %% backtrack — second answer
false.                 %% no more matches

The ; (after a query result) tells the engine to backtrack and find another answer. false means "no more."

Multiple solutions in code:

:- forall(likes(ada, X), (write(X), nl)).
%% prints math, then engines

forall(Goal, Action) runs Action for every solution of Goal.

findall/3 — collect all solutions into a list:

?- findall(X, likes(ada, X), L).
L = [math, engines].

bagof/3 — like findall but fails if no solutions; groups by free vars:

?- bagof(X, likes(ada, X), L).
L = [math, engines].

setof/3 — like bagof but sorted and de-duplicated:

?- setof(X, likes(ada, X), L).
L = [engines, math].   %% alphabetical

These collect-all predicates are essential for query-style code where you want a list of answers, not just one.

Backtracking is a feature, not a bug — but it can be expensive when it explores wrong paths. Next lesson: ! (cut) to control it.

Discussion

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

Sign in to post a comment or reply.

Loading…