【发布时间】:2015-11-24 13:26:49
【问题描述】:
假设我有两个任意列表,代表 3 位谓词的前两项:
[anna,berta,charlotte],[charles,bob,andy]
我想匹配第三个列表中的每个项目(3 位谓词的第三个项目),如下所示:
[[anna,andy],[berta,bob],[charlotte,charles]]
基本上,项目以顺序相反的方式匹配。为了按顺序匹配项目,我设计了以下代码:
match([],[],[]).
match([A|At],[C|Ct],[[A,C]|Dt]):-match(At,Ct,Dt).
但这会给我以下信息:
match([anna,berta,charlotte],[charles,bob,andy],X).
X=[[anna,charles],[berta,bob],[charlotte,andy]]
所以我需要以某种方式反转第二个列表。到目前为止,我已将代码更改如下:
match([],[],[]).
match([A|At],[C|Ct],[[A,B]|Dt]):-reverse([C|Ct],[B|Bt]),match(At,Bt,Dt).
但这会在每次通过时不断反转第二个列表。结果如下所示:
match([anna,berta,charlotte],[charles,bob,andy],X).
X=[[anna,andy],[berta,charles],[charlotte,bob]]
问题: 如何仅将第二个列表反转一次,以便实际结果与所需结果匹配?还是我的方法存在根本缺陷?我是 prolog 的新手,目前对此感到困惑。任何帮助将不胜感激。
【问题讨论】: