简体   繁体   English

列表中的 Prolog-Sum 正数

[英]Prolog-Sum positive numbers from a List

I have the following Prolog fact to sum the positive numbers from a list but it´s not working.我有以下 Prolog 事实来总结列表中的正数,但它不起作用。 What am I doing wrong?我究竟做错了什么?

somarPositivos([],0).
somarPositivos([H|T],Soma):-H>0,somarPositivos(T,Soma1),Soma is Soma1+H.
somarPositivos([H|T],Soma):-H=<0 ,somarPositivos(T,Soma1).

You have a typo in the third clause.你在第三个子句中有一个错字。 It should be:它应该是:

somarPositivos([H|T],Soma):-H=<0 ,somarPositivos(T,Soma).

Most Prolog compilers would print a warning that the variables Soma and Soma1 are singleton variables in that clause.大多数 Prolog 编译器会打印警告,指出变量SomaSoma1是该子句中的单例变量

Some notes on programming style following Prolog coding guidelines.关于遵循 Prolog 编码指南的编程风格的一些注意事项。 Indent your code.缩进你的代码。 Use spaces around operators.在运算符周围使用空格。 Use underscores instead of camelCase for predicate names for readbility.使用下划线而不是驼峰命名法作为谓词名称以提高可读性。 Thus, preferably write:因此,最好写:

somar_positivos([],0).
somar_positivos([H|T],Soma) :-
    H > 0,
    somar_positivos(T,Soma1),
    Soma is Soma1+H.
somar_positivos([H|T],Soma) :-
    H =< 0,
    somar_positivos(T,Soma).

As an improvement to this initial version of the predicate, can you rewrite it to make it tail-recursive using an accumulator?作为对谓词的初始版本的改进,您能否重写它以使用累加器使其尾递归

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

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