I'm working on Problem 26 from 99 Prolog Problems:
P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list
Example:
?- combination(3,[a,b,c,d,e,f],L). L = [a,b,c] ; L = [a,b,d] ; L = [a,b,e] ;
So my program is:
:- use_module(library(clpfd)).
combination(0, _, []).
combination(Tot, List, [H|T]) :-
length(List, Length), Tot in 1..Length,
append(Prefix, [H], Stem),
append(Stem, Suffix, List),
append(Prefix, Suffix, SubList),
SubTot #= Tot-1,
combination(SubTot, SubList, T).
My query result starts fine but then returns a Global out of stack error:
?- combination(3,[a,b,c,d,e,f],L).
L = [a, b, c] ;
L = [a, b, d] ;
L = [a, b, e] ;
L = [a, b, f] ;
Out of global stack
I can't understand why it works at first, but then hangs until it gives Out of global stack error. Happens on both SWISH and swi-prolog in the terminal.
trace? You'll probably find that, once your program finds solutions, it keeps making new, ever growing lists withappendthat it can try in order to find additional solutions which it won't ever satisfy. Your firstappend(Prefix, [H], Stem)has two variables, so those will keep growing unbounded. - lurkertraced,debugged,guitraced everything and the program always hangs after generatingL = [a, b, f] ;until the Out of stack error (actually withdebugas a first clause on the query then the error just never comes and it hangs forever). If I puttracebeforeappend(Prefix, [H], Stem)I get the following output:Call:lists:append(_14580, [_14486], _14584)Call:lists:append(_14592, [_14498], _14596)Call:lists:append(_14604, [_14510], _14608)L = [a, b, c]L = [a, b, d]L = [a, b, e]L = [a, b, f]Out of global stack- user5834035