Search code examples
prologpermutationcombinatoricsbacktrackingfailure-slice

Prolog Out of stack error


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.


Solution

  • if you try to input, at the console prompt, this line of your code, and ask for backtracking:

    ?- append(Prefix, [H], Stem).
    Prefix = [],
    Stem = [H] ;
    Prefix = [_6442],
    Stem = [_6442, H] ;
    Prefix = [_6442, _6454],
    Stem = [_6442, _6454, H] ;
    ...
    

    maybe you have a clue about the (main) problem. All 3 vars are free, then Prolog keeps on generating longer and longer lists on backtracking. As Boris already suggested, you should keep your program far simpler... for instance

    combination(0, _, []).
    combination(Tot, List, [H|T]) :- 
        Tot #> 0,
        select(H, List, SubList),
        SubTot #= Tot-1,
        combination(SubTot, SubList, T).
    

    that yields

    ?- aggregate(count,L^combination(3,[a,b,c,d,e],L),N).
    N = 60.
    

    IMHO, library(clpfd) isn't going to make your life simpler while you're moving your first steps into Prolog. Modelling and debugging plain Prolog is already difficult with the basic constructs available, and CLP(FD) is an advanced feature...