سؤال

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!

هل كانت مفيدة؟

المحلول

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).
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top