【发布时间】:2019-02-10 18:41:40
【问题描述】:
我编写了以下谓词,用于识别两个列表何时相同,除了索引 I1 和 I2 处的两个元素被交换:
swapped(I1, I2, List, NewList) :-
% The lists are the same length and the two indices are swapped.
same_length(List, NewList),
nth0(I1, List, V1), nth0(I2, List, V2),
nth0(I1, NewList, V2), nth0(I2, NewList, V1),
% All the other indices remain the same.
proper_length(List, Length), Lim is Length - 1,
numlist(0, Lim, Indices),
forall((member(I, Indices), I \= I1, I \= I2),
(nth0(I, List, V), nth0(I, NewList, V))).
以下swipl 输出说明了我的问题:
?- swapped(0, 1, [1,2,3], L).
L = [2, 1, _G5035].
?- swapped(0, 1, [1,2,3], [2,1,3]).
true.
?- swapped(0, 1, [1,2,3], [2,1,4]).
false.
既然它可以识别出3 是唯一正确的术语,为什么它会返回第三个元素的变量而不仅仅是3?这些是统一发生然后被遗忘的跟踪的最后四个部分:
Call: (10) lists:nth0(2, [2, 1, _G6121], 3) ? creep
Exit: (10) lists:nth0(2, [2, 1, 3], 3) ? creep
^ Exit: (8) forall(user: (member(_G6145, [0, 1, 2]), _G6145\=0, _G6145\=1), user: (nth0(_G6145, [1, 2, 3], _G6162), nth0(_G6145, [2, 1, _G6121], _G6162))) ? creep
Exit: (7) swapped(0, 1, [1, 2, 3], [2, 1, _G6121]) ? creep
我不怀疑有更好的方法来交换两个元素(可能是递归的),但我想知道为什么会发生这种情况以及如何解决它;我显然缺乏一些 Prolog 知识。
谢谢!
【问题讨论】:
-
forall/2仅用于测试充分实例化的目标
标签: prolog