Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 40 ยท Arithmetic and Control

Negation, If-Then-Else and Loops

Learn negation as failure with \+, the closed-world assumption, why goal order matters with negation, if-then-else with ->, and the control predicates once, ignore, forall, between and repeat.

Logic has "not", and so does Prolog, but they are not quite the same thing. Prolog's negation means "I cannot prove it". Together with if-then-else, this gives you the control constructs you need for real programs: conditions, defaults, and loops over solutions. This lesson covers \+, -> with ;, and the small predicates that make everyday code concise.

Negation as failure

The prefix operator \+ (read "not provable") succeeds when its goal fails, and fails when its goal succeeds. It never binds any variables.

PROLOG
?- \+ member(x, [a, b, c]).
true.

?- \+ member(a, [a, b, c]).
false.

This is called negation as failure. It relies on the closed-world assumption: anything that is not in the program (or not derivable from it) is taken to be false. If your database has no fact married(ann), then \+ married(ann) is true, even though Ann may be married in the real world. A Prolog program describes the world it knows.

Order matters with unbound variables

\+ only works as a test when its variables are already bound. Consider:

PROLOG
male(tom).  male(bob).
married(bob).

bachelor(X) :- male(X), \+ married(X).      % good
bad_bachelor(X) :- \+ married(X), male(X).  % wrong

In bachelor/1, male(X) binds X to tom first, so \+ married(tom) tests a concrete fact. In bad_bachelor/1, \+ married(X) runs with an unbound X. Since married(X) can succeed (with X = bob), the negation fails immediately, and the predicate finds no answers at all, not even for tom. The rule is: generate first, then test. Bind the variable with a positive goal, and only then apply \+.

The stand-in engine below runs both. It is a small Python interpreter for facts, rules, the cut, \+ and if-then-else, written to behave like Prolog on these programs.

Python Generate first, then negate (Python stand-in engine)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

\+ has another use: it is the cleanest way to say "different". X \= Y is shorthand for \+ X = Y. When you need "these two are different people", write X \= Y after both are bound.

If-then-else

( Condition -> Then ; Else ) is Prolog's conditional:

  1. Prove Condition. If it has a solution, take the first one, discard the others, and run Then.
  2. If Condition fails, run Else.
PROLOG
sign(N, S) :-
    (   N > 0 -> S = positive
    ;   N < 0 -> S = negative
    ;   S = zero
    ).
PROLOG
?- sign(-4, S).
S = negative.

Chain as many branches as you like with ; Cond -> Then. The final ; Else is the default. Format the parentheses as above, with the operators at the start of lines; it reads like an if / else if / else and keeps the nesting visible.

Two details matter:

  • The condition is committed: ( member(X, [1,2,3]) -> ... ) uses only X = 1. This is like an implicit cut after the condition.
  • Without an else part, ( Cond -> Then ) fails when Cond fails. If you want "do nothing" instead, write ( Cond -> Then ; true ).

The soft-cut operator *-> keeps all solutions of the condition: ( Cond *-> Then ; Else ). It is rarely needed but good to know it exists.

Python If-then-else versus cut (Python stand-in engine)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Small control predicates

Many everyday patterns already have a name in SWI-Prolog:

Predicate Meaning
once(G) run G, keep only the first solution
ignore(G) run G once; succeed whether or not it succeeded
forall(Cond, Action) true if Action holds for every solution of Cond
between(L, H, X) enumerate integers from L to H
repeat succeed forever on backtracking (use with a cut)
fail / true always fail / always succeed

forall/2 is defined as \+ ( Cond, \+ Action ): "there is no solution of Cond for which Action fails". It is the right tool for checking a property over all items and for printing every solution:

PROLOG
?- forall(member(X, [2, 4, 6]), 0 is X mod 2).
true.

?- forall(between(1, 3, N), (Sq is N * N, format("~w squared is ~w~n", [N, Sq]))).
1 squared is 1
2 squared is 4
3 squared is 9
true.

The second query is Prolog's idiom for a failure-driven loop: between/3 produces solutions by backtracking and forall runs the action on each, then true at the end. The older spelling, still common, is:

PROLOG
print_squares :-
    between(1, 3, N),
    Sq is N * N,
    format("~w squared is ~w~n", [N, Sq]),
    fail.
print_squares.

The final clause makes the predicate succeed after the loop has exhausted all solutions. Because variables cannot be reassigned, there is no counter to increment; the loop gets its values from backtracking.

repeat is for loops that read input or retry until a condition holds:

PROLOG
read_until_stop :-
    repeat,
    read(Term),
    process(Term),
    Term == stop,
    !.

The cut at the end stops repeat from running forever after the stop condition is met.

Common mistakes

  • Using \+ with unbound variables and expecting it to enumerate "all things that are not X". It can only test.
  • Forgetting the else part and being surprised that the clause fails.
  • Writing ( A -> B ), C and expecting the arrow to bind A's alternatives; it commits to the first one.
  • Thinking \+ \+ G is silly: it is a useful test that keeps no bindings (it succeeds if G succeeds, and discards the answer).
  • Confusing \= with "not equal numerically": for numbers use =\=.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does \+ member(z, [a, b]) answer?

    member(z, [a, b]) fails, so its negation as failure succeeds.
  2. 2. Why does bad(X) :- \+ married(X), male(X). find no bachelors when someone is married?

    With X unbound, married(X) can succeed, so + fails. Generate X with male(X) first, then negate.
  3. 3. What happens to ( Cond -> Then ) when Cond fails?

    Without an else branch, the if-then fails. Add ; true to do nothing instead.
  4. 4. Which goal checks that every element of a list is positive?

    forall(Cond, Action) is true when Action holds for every solution of Cond.

Summary

  • \+ G succeeds when G cannot be proved: negation as failure under the closed-world assumption.
  • Bind variables with a positive goal before using \+, or the test will not mean what you think.
  • ( C -> T ; E ) commits to the first solution of C; without ; E it fails if C fails.
  • once/1, ignore/1, forall/2, between/3 and repeat cover most loops and defaults.
  • Failure-driven loops use backtracking in place of counters.

Next: Compound Terms and Structures