计算子句的调用次数 [英] count the number of calls of a clause
问题描述
我有一个类似如下的子句:
lock_open:-条件组合(X),等于(X,[8,6,5,3,6,9]),!,打印(X).
此子句成功.但我想知道在 equal(X,[8,6,5,3,6,9])
变为真之前调用了多少次 conditional_combination().该程序是通过遵循一些规则来生成一个排列.而且我需要生成多少排列才能获得像 865369 这样的特定值.
你真正想要的是稍微不同的东西:你想计算一个目标的答案数量(到目前为止).
以下谓词 call_nth(Goal_0, Nth)
与 call(Goal_0)
一样成功,但有一个附加参数,表明找到的答案是第 n 个答案.此定义高度特定于 SWI 或 YAP.不要不要在你的一般程序中使用像 nb_setarg/3
这样的东西,而是将它们用于封装良好的情况,就像这个一样.甚至在对于这两个系统,这些构造的确切含义对于一般情况没有很好的定义.这里是 SICStus 的定义.
Eclipse 提供了更强大的抽象:
call_nth(Goal_0, Nth) :-架子创建(计数器(0),CounterRef),呼叫(目标_0),Shelf_inc(CounterRef, 1),shelf_get(CounterRef, 1, Nth).
<上一页>?- call_nth((1,5,I),Nth).我 = 第 N, 第 N = 1 ;我 = 第 N,第 N = 2;我 = 第 N,第 N = 3;我=第N次,第N次= 4;我 = 第 N 个,第 N 个 = 5.
所以简单地把它包裹起来:
<上一页>lock_open :-call_nth(conditional_combination(X), Nth),X = [8,6,5,3,6,9],!,……I have a clause like following:
lock_open:- conditional_combination(X), equal(X,[8,6,5,3,6,9]),!, print(X).
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.
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.
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.
So simply wrap it around:
lock_open :- call_nth(conditional_combination(X), Nth), X = [8,6,5,3,6,9], !, ....
这篇关于计算子句的调用次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!