-1

I have written the following program to compute all pairs of members in a list. Here is my code:

select_pair(X, Y, [X|[Y|T]], T).
select_pair(X, Y, [Head|[X|[Y|T]]], [Head|Rest]) :- select_pair(X, Y, T, Rest).

I am supposed to call my code with this 3-member list only:

select pair(X, Y, [1,2,3], Zs).

But this doesn't generate all possible combinations. It only generates

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

and it is supposed to generate this, but it does not:

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, how can I modify this code to generate all possible pairs of members of the list [1, 2, 3]?

1 Answer 1

2

I'd use procedure select/3:

select_pair(X, Y, List, Rest):-
  select(X, List, MList),
  select(Y, MList, Rest).

The first select would remove the first element from List into X and put the rest of the list in MList.

Then the second select would get you the second element and the Rest.

1
  • Excellent. never mind my prev. comment. I just saw how you modified select/3. Works like a charm. Thanks Dec 2, 2014 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.