Skip to content
Rules and Recursion
step 1/4

Reading — step 1 of 4

Learn

~1 min readRecursion and Lists

A rule has a head and a body — the head is true if the body is provable:

adult(X) :- age(X, A), A >= 18.

age(ada, 36).
age(bob, 12).

% adult(ada) succeeds. adult(bob) fails.

Recursion is the only way to loop in pure Prolog. The classic factorial:

factorial(0, 1).
factorial(N, F) :-
    N > 0,
    N1 is N - 1,
    factorial(N1, F1),
    F is N * F1.

Note the arithmetic rules:

  • X is Expr evaluates Expr and binds X to the result
  • Variables in Expr must already be bound
  • = is unification (used for matching), not assignment
  • =:= compares numerical values: 2 + 2 =:= 4 is true

The recursion has a base case (factorial(0, 1)) and a recursive case. Prolog tries clauses in order — base case first matters.

Discussion

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

Sign in to post a comment or reply.

Loading…