计算一个子句的调用次数 [英] count the number of calls of a clause

查看:39
本文介绍了计算一个子句的调用次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面这样的子句:

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 的定义.

<前>call_nth(Goal_0, C) :-State = count(0,_), % 注意仍然是变量的额外参数目标_0,arg(1,状态,C1),C2是C1+1,nb_setarg(1, 状态, C2),C = C2.

Eclipse 提供了更健壮的抽象:

call_nth(Goal_0, Nth) :-货架创建(计数器(0),CounterRef),呼叫(目标_0),shelf_inc(CounterRef, 1),shelf_get(CounterRef, 1, Nth).

<前>?- call_nth( between(1,5,I),Nth).I = 第 N 个,第 N 个 = 1 ;I = 第 N 个,第 N 个 = 2 ;I = 第 N 个,第 N 个 = 3 ;I = 第 N 个,第 N 个 = 4 ;I = 第 N 个,第 N 个 = 5.

所以简单地将它包裹起来:

<前>锁打开:-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆