Count the number of item calls

I have a suggestion like:

  lock_open: -
         conditional_combination (X),
         equal (X, [8,6,5,3,6,9]),!,
         print (X).

This item is doing well. But I want to know how many times conditional_combination () is called before equal(X,[8,6,5,3,6,9]) becomes true. the program must generate a permutation following some rules. And I need how many permutations I need to generate in order to get a specific value, for example, 865369.

+12
count recursion prolog
Jul 06 2018-12-12T00:
source share
2 answers

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]
    !
    ....
+12
Jul 9 '12 at 17:41
source share

If you use the SWI prolog, you can use nb_getval/2 and nb_setval/2 to achieve the desired result:

 lock_open:- nb_setval(ctr, 0), % Initialize counter conditional_combination(X), nb_inc(ctr), % Increment Counter equal(X,[8,6,5,3,6,9]), % Here you can access counter value with nb_getval(ctr, Value) !, print(X). nb_inc(Key):- nb_getval(Key, Old), succ(Old, New), nb_setval(Key, New). 

Other prologs have other ways to do the same; look for global variables in your prolog implementation. In this snippet, I used the term ctr to store the current target counter. You can use any term there that is not used in your program.

+4
Jul 06 '12 at 17:30
source share



All Articles