简体   繁体   English

事实列表中所有实例的序言总和

[英]Prolog Sum of All Instances in a List of Facts

I have a list of facts. 我有一个事实清单。 Each fact defines a relationship between two subjects and the number of projects they've completed. 每个事实都定义了两个主题及其完成的项目数量之间的关系。 They're defined like this: 它们的定义如下:

label(allGroups,[group(a,b,10),group(b,c,3),group(c,d,12)]).

I'm trying to write a function that will make a list of all the projects completed by an individual. 我正在尝试编写一个函数,该函数将列出一个人完成的所有项目的列表。 For example, 'b' has completed a total of 13 projects while c has completed a total of 15 projects. 例如,“ b”总共完成了13个项目,而“ c”总共完成了15个项目。

This is the function I've got going right now. 这是我现在要执行的功能。

individualSum([],_,0).
individualSum([group(Name,_,Projects)|Tail],Name,Sum) :-
    individualSum(Tail,Name,Tailsum),
    Sum is Projects + Tailsum.
individualSum([group(_,Name,Projects)|Tail],Name,Sum) :-
    individualSum(Tail,Name,Tailsum),
    Sum is Projects + Tailsum.

I keep getting false and can't figure out if that's due to an incomplete basecase for the recursion or something else entirely. 我不断弄虚作假,无法弄清楚这是由于递归的基数不完整还是其他原因。 Here's what I'm running: 这是我正在运行的:

?- [groupSum].
?- label(allGroups,L),Groups=L).

(spits out allGroups, then:) (吐出allGroup,然后:)

?- individualSum($Groups,b,Total).
false.

Any idea where I'm going wrong? 知道我哪里出错了吗? I appreciate any help I can get. 感谢您能提供的任何帮助。

You need to add another clause to skip groups here neither of the subjects is the one you are looking for: 您需要添加另一个子句以跳过组,此处没有一个主题正在寻找:

individualSum([group(Name1,Name2,Projects)|Tail],Name,Sum):-
  Name \= Name1,
  Name \= Name2,
  individualSum(Tail,Name,Sum).

Gusbro already spotted the problem (+1). Gusbro已经发现了问题(+1)。 Since you're using SWI-Prolog, you could do with an aggregation builtin. 由于您使用的是SWI-Prolog,因此可以使用内置的聚合功能

individualSum(L,Name,Sum) :-
    aggregate_all(sum(Projects),
       ( member(group(A,B,Projects), L), ( A = Name ; B = Name )), Sum).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM