8.3.2 Failure Driven Loops

The idea of failure driven loops is to force Prolog to backtrack until there are no more possibilities left.

The idea of failure driven loop s is to force Prolog to backtrack until there are no more possibilities left. How can we force Prolog to backtrack? Well, Prolog automatically tries to backtrack when it fails. So, adding a goal which always fails (such as the built in predicate fail/0 which has no effect but to make Prolog fail) at the end of a clause, will force Prolog to backtrack over all the other goals in that clause until it has tried all the possibilities. Here is an example:

write_everybody_happy :- happy(X),
                         write(X),nl,
                         fail.
write_everybody_happy :- true.

If you consult this little program and the ask Prolog the query write_everybody_happy, Prolog will look up in its database all objects that make happy(X) true and will print them out on the screen. So, if the database looked as follows

happy(harry).
happy(ron).
happy(hermione).
happy(hagrid).

Prolog would write on the screen

harry
ron
hermione
hagrid
 
yes


Kristina Striegnitz, Patrick Blackburn, Katrin Erk, Stephan Walter, Aljoscha Burchardt and Dimitra Tsovaltzi
Version 1.2.5 (20030212)