Visual Prolog 5.2:一种奇怪的回溯行为

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月6日 06:45:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定