Reputation: 179
[a,b,c,d] and
[[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]]
I want to make
[[a,1,2,3,4],[b,5,6,7,8],[c,43,34,56,5],[d,23,32,2,2]]
I use swi prolog is it possible do it ?
Thanks a lot.
Upvotes: 3
Views: 311
Reputation: 18726
Use meta-predicate maplist/4
and Prolog lambdas like this:
?- As = [a,b,c,d],
Bss = [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]],
maplist(\H^T^[H|T]^true,As,Bss,Css).
As = [ a , b , c , d ],
Bss = [[ 1,2,3,4],[ 5,6,7,8],[ 43,34,56,5],[ 23,32,2,2]],
Css = [[a,1,2,3,4],[b,5,6,7,8],[c,43,34,56,5],[d,23,32,2,2]].
Different lambda terms can be used in above maplist/4
goal, as pointed out in a comment.
maplist(\H^T^[H|T]^true,As,Bss,Css)
maplist(\H^T^ =([H|T]) ,As,Bss,Css)
Upvotes: 2
Reputation: 5565
SWI Prolog can do this with two short predicates:
merge0(A, B, Prev, Next) :- append(Prev, [[A|B]], Next).
merge(A, B, Result) :- foldl(merge0, A, B, [], Result).
Here is example of input and output:
a(X) :- X = [a,b,c,d].
b(X) :- X = [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]].
?- a(A), b(B), merge(A, B, Result).
Result = [[a, 1, 2, 3, 4], [b, 5, 6, 7, 8], [c, 43, 34, 56, 5], [d, 23, 32, 2, 2]].
Upvotes: 1
Reputation: 17262
solve([], [], []).
solve([[X|Y]|S], [X|L1], [Y|L2]):-
solve(S, L1, L2).
UPDATE: How to use
Write the function in a file "a.pl", then in swi-prolog type:
['a.pl'].
then type:
solve(X, [a,b,c,d], [[1,2,3,4],[5,6,7,8],[43,34,56,5],[23,32,2,2]]).
You will get:
X = [[a, 1, 2, 3, 4], [b, 5, 6, 7, 8], [c, 43, 34, 56, 5], [d, 23, 32, 2, 2]]
I have the strange feeling that I am doing your homework. Is it?
Upvotes: 2
Reputation: 2232
try this:
delete(X, [X|T], T).
delete(X, [Y|T], [Y|L]):-
delete(X, T, L).
insert(X, List, BigList):-
delete(X, BigList, List).
if([],X,X).
if([H1|T1],[H2|T2],[SH|ST]):-
insert(H1,H2,SH),!,
if(T1,T2,ST).
I doubled checked, it works.
"if" stands for "insert first".
Upvotes: 0