theG
theG

Reputation: 23

Prolog list combinations

I'm trying to write a prolog code which will take a list and return all pairs of each element of that list. So for example:

   X = 1, Y = 2, Zs = [3] ;
   X = 1, Y = 3, Zs = [2] ;
   X = 2, Y = 1, Zs = [3] ;
   X = 2, Y = 3, Zs = [1] ;
   X = 3, Y = 1, Zs = [2] ;
   X = 3, Y = 2, Zs = [3]

So far I am able to get uptil the third line and not able to get the rest of the output. My code is:

select_pair(X,Y,[X|Xs],Zs):- select(Y,Xs,Zs).
select_pair(X,Y,[H|Z1],[H|Z2]):- select_pair(X,Y,Z1,Z2).

Upvotes: 2

Views: 389

Answers (1)

Steven
Steven

Reputation: 2477

In words, what you want to achieve is:

  • Take any X from the input list
  • Take any Y different from X from the input list
  • Elements other than X and Y are in Zs

This translates quite easily into a prolog predicate:

select_pair(X, Y, L, Zs) :-
    select(X, L, Xs),
    select(Y, Xs, Zs).

First we select X from the input L. From the remaining elements Xs we select Y. After this, the remaining elements is Zs.

Upvotes: 2

Related Questions