计算一个子句的调用数 [英] count the number of calls of a clause
问题描述
我有一个如下的子句:
lock_open:-
conditional_combination(X),
equal(X,[8,6,5,3,6,9]),!,
print(X).
此子句成功。但是我想知道在 equal(X,[8,6,5,3,6,9])
变为true之前调用conditional_combination()多少次。该程序通过遵循一些规则来生成置换。
this clause succeed. But I want to know how many times conditional_combination() is called before equal(X,[8,6,5,3,6,9])
is become true. the program is to generate a permutation by following some rules. And I need to how many permutation is need to generate to get a particular value like 865369.
推荐答案
你真正想要的是什么稍微不同:你想计算目标的回答数目(到目前为止)。
What you actually want is something slightly different: You want to count the number of answers (so far) of a goal.
以下谓词 call_nth(Goal_0,Nth)
成功如调用(Goal_0)
,但有一个附加的参数,表示找到的答案是第n个答案。此定义高度特定于SWI或YAP。在一般程序中不使用 nb_setarg / 3
,但将其用于这种封装的情况。即使在
这两个系统中,这些结构的精确含义也没有很好地定义为一般情况。 这里是SICStus 的定义。
The following predicate call_nth(Goal_0, Nth)
succeeds like call(Goal_0)
but has an additional argument which indicates that the answer found is the n-th answer. This definition is highly specific to SWI or YAP. Do not use things like nb_setarg/3
in your general programs, but use them for well encapsulated cases as this one. Even within
those two systems, the precise meaning of these constructs is not well defined for the general case. Here is a 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.
Eclipse提供了更强大的抽象:
A more robust 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.
因此,只需将其包装:
lock_open :-
call_nth(conditional_combination(X), Nth),
X = [8,6,5,3,6,9],
!,
....
这篇关于计算一个子句的调用数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!