I’m trying to generate multiple permutations using this code:
:- use_module(library(clpfd)).
p(N, Indexes) :-
M in 1..N,
M #=< N,
length(Indexes, M),
Indexes ins 1..N.
It returns me all the results, but in the end crashes with ERROR: Out of global stack
What happens in your code is that the length of the list is implicitly set by calling
length/2. This will start with a list of length 0, which bindsMto 0, which in turn wakes up the constraintM in 1..N, which fails. Next it returns a list of length 1, which succeeds, then on backtracking a list of length 2, which succeeds again. After that, any further backtracking intolength/2will return longer and longer lists, but wakingM in 1..Nwill always fail until the list becomes so large that you run out of memory.What you need to do is place the choicepoint before the
length/2call instead of inside of it by, e.g., replacing(which is a redundant constraint anyway) with
This gives you: