简体   繁体   English

PROLOG根据事实创建的列表的总和

[英]PROLOG Sum of a list created from facts

I want to create a list from the facts. 我想根据事实创建一个列表。 And the list should contains only one of the arity in the facts. 并且列表应仅包含事实中的一种。

For example : 例如 :

%facts
abc(a, b, c).
abc(d, e, f).
abc(g, h, i).

Sample : 样品:

?-lists(A).
  A = [a, d, g];
  No.

EDIT : 编辑:

Using the suggestion by Vaughn Cato in the comment, the code become this : 使用Vaughn Cato在评论中的建议,代码变为:

%facts
abc(a, b, c).
abc(d, e, f).
abc(g, h, i).

lists(A) :-
    findall(findall(X, abc(X, _, _), A).

The list is created, but how to sum up the list A ? 列表已创建,但是如何对列表A求和?

If sum of list for input from query, 如果是来自查询的输入清单的总和,

sumlist([], 0).
sumlist([X|Y], Sum) :-
    sumlist(Y, Sum1),
    Sum is X + Sum1.

But if want to sum the existing list, how to define the predicate? 但是如果要对现有列表求和,如何定义谓词?

To sum a list of numbers such as that produced by your definition of lists/1 , most Prolog systems (eg, GNU , SWI ) implement sum_list/2 which takes a list of numbers as the first argument and binds their sum in the second: 要对数字列表求和,例如由lists/1定义所产生的数字,大多数Prolog系统(例如GNUSWI )实现sum_list/2 ,它将数字列表作为第一个参数,并将其和绑定在第二个参数中:

?- sum_list([1,2,3],Sum).
Sum = 6.

You can also solve it with aggregate_all/3. 您也可以使用aggregate_all / 3解决。 It eliminates need to build list in memory if you just need a sum. 如果您只需要一个总和,它就不需要在内存中建立列表。

sum_facts(Template, Arg, Sum) :-
   aggregate_all(sum(X), (call(Template), arg(Arg, Template, X)), Sum).

In this example I use a generic call with defined Template: 在此示例中,我使用定义了模板的通用调用:

sum_facts(abc(_, _, _), 1, Sum).

If you will always use it with the first arg of abc/3 this version will be enough: 如果您始终将其与abc / 3的第一个参数一起使用,则此版本就足够了:

sum_facts(Template, Arg, Sum) :-
   aggregate_all(sum(X), abc(X, _, _), Sum).

As suggested by Vaughn Cato, it's help me a lot by using findall(X,abc(X, _ , _ ),A). 正如Vaughn Cato所建议的那样,通过使用findall(X,abc(X, _ , _ ),A).可以对我有很大帮助findall(X,abc(X, _ , _ ),A). to create the list I wanted to. 创建我想要的列表。

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

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