我遇到了这个初学者问题,我不知道如何解决这个问题。这里是我的代码:在递归/回溯中积累
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总和c osts,但我不知道该怎么做。我想用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;
谁能告诉现在什么是问题呢?
我会尝试的findall然后,我会后我尝试 – user1598696
我做了关于你提出 – m09
感谢代码的编辑对我的回答它的工作原理: ) – user1598696