3
[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.

selda
  • 179
  • 1
  • 2
  • 6

4 Answers4

2

Use 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]].

Edit

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)
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
  • 2
    Alternatively: `..., maplist(\H^T^ =([H|T]),As,Bss,Cs).` – false Aug 04 '15 at 13:40
  • @false. Smart! Nice combination of lambda args + compound (for partial application of goal). Should be part of a Prolog lambda tutorial... – repeat Aug 04 '15 at 13:44
2
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?

Vincent Cantin
  • 16,192
  • 2
  • 35
  • 57
1

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]].
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40
0

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".

Andro
  • 2,232
  • 1
  • 27
  • 40