英文:
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).
英文:
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.
答案1
得分: 2
回溯发生在目标失败时,但 contain([H|_], H) :- write("up"), nl.
是成功的。
查询 contain([4,4,2,3,2], 2)
得到满足,列表包含了一个2。代码表示没有其他操作要执行。如果你希望它继续遍历列表,你需要将这行代码改成 nl, fail.
以触发回溯,或者添加一个递归调用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论