Search code examples
prologvisual-prolog

Visual Prolog 5.2: a odd backtracking behavior


predicates
/*....*/
clauses
contain([H|_], H) :- write("up"), nl.
contain([_|L], N) :- contain(L, N).
goal
contain([4,4,2,3,2], 2).

I have this little program in prolog it supposed to yell "up" whenever it encounters N in the list, this should work because of the backtracking mechanism of prolog, when we find that N marches the Head of the list, the first clauses is satisfied and "up" is printed, but prolog should back track and continue with the second clauses any way, witch will ensure the we search the whole list. but prolog did not it stops at the first occurrence on N, I can solve the issue by adding a contain(L, N) recursion call in the first clause I think, but I don't wont do that, i wont to understand why the first version don't work properly.


Solution

  • Backtracking happens on goal failures, but contain([H|_], H) :- write("up"), nl. is a success.

    The query contain([4,4,2,3,2], 2) is satisfied, the list contains a 2. The code says there is nothing else to do. If you want it to keep walking the list you need to change the line to end in nl, fail. to trigger backtracking, or add a recursive call.