What you really want is a little different: you want to count the number of answers (so far) of the goal.
The following predicate call_nth(Goal_0, Nth) succeeds as call(Goal_0) , but has an additional argument that indicates that the answer found is the nth answer. This definition is very specific to SWI or YAP. Do not use things like nb_setarg/3 in your shared programs, but use them for well-encapsulated cases like this. Even inside these two systems, the exact meaning of these constructions is not sufficiently defined for the general case. Here is the definition for SICStus .
call_nth (Goal_0, C): -
State = count (0, _),% note the extra argument which remains a variable
Goal_0,
arg (1, State, C1),
C2 is C1 + 1,
nb_setarg (1, State, C2),
C = C2.
A more efficient abstraction is provided by Eclipse:
call_nth(Goal_0, Nth) :- shelf_create(counter(0), CounterRef), call(Goal_0), shelf_inc(CounterRef, 1), shelf_get(CounterRef, 1, Nth).
? - call_nth (between (1,5, I), Nth).
I = Nth, Nth = 1;
I = Nth, Nth = 2;
I = Nth, Nth = 3;
I = Nth, Nth = 4;
I = Nth, Nth = 5.
So just wrap it:
lock_open: -
call_nth (conditional_combination (X), Nth),
X = [8,6,5,3,6,9]
!
....