user7630822
user7630822

Reputation: 51

how to generate all combinations of 2 lists in prolog

I need to generate combinations of 2 lists which have 4 elements each.

For example, list([1,2,3,4],[x,y,w,z],L). should return

L = [(1,x),(1,y),(1,w),(1,z),(2,x),(2,y)|...] as the answer.

This is my code:

comb([],[],[]).
comb([H1|_],[H2|_],[H1|H2]).
comb([_|T1],[_|T2],L):- comb(T1,T2,L).

... and it prints:

L = [1|y] ;
L = [2|x] ;
L = [].

... which is not the correct answer. Can someone help me to fix this?

Upvotes: 0

Views: 2304

Answers (1)

lurker
lurker

Reputation: 58284

Your problem can be expressed as:

Find all pairs (X, Y) such that X is a member of List1 and Y1 is a member of List2.

This can be directly translated into Prolog:

list_pairs(List1, List2, Pairs) :-
    findall((X,Y), (member(X, List1), member(Y, List2)), Pairs).

Upvotes: 2

Related Questions