1

I am writing a function that returns distinct sublists of a size n.

When I run the following prolog code with a query gen_list_n(4,D,[1,2,3,4]) it runs into an infinite loop after returning the first answer. How do I prevent this?

member_rem(E,L,R) :- 
append(X,Y,R), 
append( X ,[E], L0), 
append( L0,Y, L).

gen_list_n(0,[],_).

gen_list_n(N,[X|Xs],L) :- 
N > 0, 
N1 is N-1, 
member_rem(X,L,R), 
gen_list_n(N1,Xs,R).

1 Answers1

0

member_rem/3 is called with only L instantiated, then the first 2 member/3 on backtracking generate infinite lists.

Here a snapshot of member_rem' variables after some backtrack step:

L   = [4]
R   = [_G5662, _G5668, _G5674, _G5680|Y]
X   = [_G5662, _G5668, _G5674, _G5680]
L0  = [_G5662, _G5668, _G5674, _G5680, E]

I think you should rephrase member_rem in simpler way. Could be appropriate a simple select/3. Using that, I get

member_rem(E,L,R) :-
    select(E, L, R).

?- gen_list_n(4,D,[1,2,3,4]).
D = [1, 2, 3, 4] ;
D = [1, 2, 4, 3] ;
D = [1, 3, 2, 4] ;
...
CapelliC
  • 59,646
  • 5
  • 47
  • 90