1

我正在尝试找到一种将列表附加到列表中所有列表的方法。

就像是:

appendAll([a,b],[[q,w],[z,x]],X).
X = [[a,b,q,w],[a,b,z,x]].

我对 prolog 还是很陌生,嵌套列表让我很失望。

我已经盯着这个几个小时了:

appendAll([], _, []).
appendAll(_, [], []).
appendAll([H1|T1], [H2|T2], X) :-
  append(H1,H2,R),
  appendAll(T1,[H2|T2],X).
  % recurse down to [], and append back up

非常感谢任何帮助谢谢!

4

1 回答 1

3

使用 Prolog 编程的困难在于习惯和识别背后的实际递归模式。在许多情况下,最好不要直接考虑递归,而是询问一些简单的所有构造是否可以在这里工作。

在这种情况下,您需要一个列表列表和另一个列表列表之间的关系。两者的长度相同,因为元素在元素方面相互对应。

appendAll(Prefix, Lists, Prefixedlists) :-
    maplist(append(Prefix), Lists, Prefixedlists).

谓词maplist/3在许多 Prolog 系统中都有定义。如果不是,请在符合 ISO 的系统中这样定义:

maplist(_Cont_2, [], []).
maplist(Cont_2, [X|Xs], [Y|Ys]) :-
   call(Cont_2, X, Y),
   maplist(Cont_2, Xs, Ys).

这是相同的,作为一个简单的谓词:

maplist_append(Prefix, [], []).
maplist_append(Prefix, [X|Xs], [Y|Ys]) :-
   append(Prefix, X, Y),
   maplist_append(Prefix, Xs, Ys).
于 2012-02-19T01:46:53.140 回答