【问题标题】:Prolog unifies a variable with a term then forgets the unificationProlog 将变量与术语统一然后忘记统一
【发布时间】:2019-02-10 18:41:40
【问题描述】:

我编写了以下谓词,用于识别两个列表何时相同,除了索引 I1I2 处的两个元素被交换:

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


【解决方案1】:

forall/2 是所谓的“failure driven loop”。然后在循环之间撤消实例化。

在 SWI-Prolog 中,有 foreach/2,它解决了您的第一个查询问题。

...
numlist(0, Lim, Indices),
foreach((member(I, Indices), I \= I1, I \= I2),
       (nth0(I, List, V), nth0(I, NewList, V))).

测试:

?- swapped(0, 1, [1,2,3], L).
L = [2, 1, 3].

在 SWI-Prolog 中,有时更好的理解内置函数的方法是检查源代码。您可以看到 foreach/2 是一个相当复杂的谓词...在 swipl 提示符下,尝试?- edit(foreach).,或点击文档页面中的源链接(带圆圈的:-)。

【讨论】:

  • 很高兴看到edit(foreach). 的使用,请继续提供这些提示。
  • 啊,谢谢!我以为我尝试过 foreach 虽然我不明白其中的区别,但我想我还没有尝试过使用谓词的最终版本。也感谢edit 的提示。
  • \=/2 ---> =\=/2
猜你喜欢
  • 2020-02-27
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多