在递归/回溯中累积

时间:2012-09-03 23:39:12

标签: prolog

我遇到这个初学者问题,我不知道如何解决这个问题。这是我的代码:

worker( w1, d1, 2000 ) .    
worker( w2, d1, 2500 ) .
worker( w2, d2, 1000 ) .
worker( w3, d2, 2000 ) .
worker( w4, d2, 4000 ) .

% worker( W, D, S ) means that worker W works in department D and has salary S

department( d1, w2 ) .
department( d2, w4 ) .

% department( D, B ) means that worker B is director of department D(this is not important in this case)

我需要从部门中获得所有工资的总和,如下:

?- department_costs( d1 , T ) .
T = 4500;
no
?- department_costs( D, T ) .
D = d1
T = 4500;
D = d2
T = 7000;
no
?- department_costs( d3 , T ) .
no

我试过了:

department_costs( D, T ):- worker( _X, D, T1 ), T is T1.

我明白了:

?- department_costs( o1, T ).
T=2000;
T=2500;
no

现在我需要总结T + T总成本,但我不知道该怎么做。我想使用findall / setof / bagof解决这个没有

修改

我尝试使用findall:

sumL([], 0).
sumL([G|R], S):-
   sumL(R, S1),
   S is S1 + G.

department_costs( D, T ):-
   findall(P, worker( _X, D, P ), R ),
   sumL(R, S),
   T=S.

它可以与department_costs(d1,T)和department_costs(d2,T)一起使用,但是当我输入department_costs(D,T)时。我明白了:

 department_costs( D, T ).
 O=_h159
 T=11500

它应该是这样的:

 ?- department_costs( D, T ) .
 D = d1
 T = 4500;
 D = d2
 T = 7000;

有人能说出现在的问题吗?

4 个答案:

答案 0 :(得分:5)

想要在没有findall/3的情况下解决此问题只会导致重新编码所述findall/3的尝试不佳。如果您真的想跳过findall/3,请以不同的方式表示您的数据,例如:

workers([w1-d1-2000, w2-d1-2500, w2-d2-1000, w3-d2-2000, w4-d2-4000]).
departments([d1-w2, d2-w4]).

在这种格式中,您将能够使用递归和列表处理技术来获得良好的结果。在前一个中,您将不得不使用数据库操作和/或全局变量。不是Prolog-ish。

对于您的编辑,问题是您使用findall/3,而findall/3将为您提供您感兴趣的一个变量的所有结果,但不会精确显示导致的绑定对那些结果。

请尝试bagof/3

bagof(S, W^worker( W, D, S ), R ).

请参阅此man page(即使它是SWI,无论如何都是ISO Prolog谓词)以获取更多信息。

答案 1 :(得分:5)

库(aggregate)旨在解决这类问题。值得研究。

department_costs( D, T ) :- aggregate_all(sum(C), worker( _, D, C ), T).

修改

XSB有“Tabling Aggregate Predicates”,可以让您有效地解决问题。

答案 2 :(得分:1)

粗略的,并且收回每个工人使用的事实,但是会做到这一点:

department_costs(D,T) :- worker(X,D,T1), retract(worker(X,D,T1)), department_costs(D,T2), T is T1+T2).
department_costs(_,0).

一个破坏性较小的替代方法是传递到目前为止使用的工作者列表,验证将要使用的任何工作者不在列表中,并将新使用的工作者添加到列表中以进行递归调用。 (我想你可以在递归调用返回后重新断言子句末尾的缩回事实,但这感觉真的太烂了。)

答案 3 :(得分:1)

我没有测试过这个,但想法是你积累了你已经算过的工人。 我真的不喜欢它,如果我发现超过几分钟,我相信你可以在没有邪恶切割的情况下以更具声明性的方式做到这一点。

department_sum(S, D) :- 
        department_sum_agg([], S, D).

department_sum_agg(Workers, S, D) :- 
    worker(X,D,SX), 
    \+ member(X, Workers), !,
    department_sum_agg([X|Workers], SRest, D),
    S is SX + SRest.

department_sum_agg(_, 0, _).