appendAll - Append a list to all lists within a list

孤街浪徒 提交于 2019-12-11 04:38:59

问题


I'm trying to find a way to append a list to all lists within a list.

Something like:

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

I'm still new to prolog and nested lists are throwing me off quite a bit.

I've been staring at this for a few hours now:

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

Any help is much appreciated Thanks!


回答1:


What is difficult in programming with Prolog is to get used to and identify the actual recursion patterns behind. In many cases it is best not to think in recursions directly, but rather ask if some simple for all construct might work here.

In this case, you want a relation between a list of lists and another list of lists. Both are of same length, as the elements correspond to each other element-wise.

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

The predicate maplist/3 is defined in many Prolog systems. If not, define it like so in an ISO conforming system:

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

Here is the same, as a plain predicate:

maplist_append(Prefix, [], []).
maplist_append(Prefix, [X|Xs], [Y|Ys]) :-
   append(Prefix, X, Y),
   maplist_append(Prefix, Xs, Ys).


来源:https://stackoverflow.com/questions/9345709/appendall-append-a-list-to-all-lists-within-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!