我想计算列表中的正元素(VIsual Prolog)。所以我写了这个函数:
positiveCount([], C).
positiveCount([A], C) :- A > 0, C = C + 1.
positiveCount([H|T], C) :- H > 0,!,C = C+1,positiveCount(T,C); positiveCount(T,C).
错误:
The flow pattern '(o,i)' does not exist for '+' main.pro
据我从这个错误中了解到,我不能将 C 的 C=C+1
用作输入变量。
有什么办法可以修复我的代码吗?
最佳答案
以下代码使用clpfd在 swi-prolog ,所以不要期望它在 visual-prolog 上按原样运行:-(
不过,我希望它对你有用!
:- use_module(library(clpfd)). count_pos([], 0). count_pos([E|Es], C) :- E #=< 0, count_pos(Es, C). count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
Let's read the clauses in plain English in the direction of the "arrow" :-
, that is "right to left".
count_pos([], 0).
The number of positive arithmetic expressions contained in the empty list
[]
is zero.count_pos([E|Es], C) :- E #=< 0, count_pos(Es, C).
If list
Es
containsC
positive arithmetic expressions
and if some arithmetic expressionE
is not positive
then conclude that[E|Es]
also containsC
positive arithmetic expressions.count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
If list
Es
containsC0
positive arithmetic expressions
and if some arithmetic expressionE
is positive
then conclude that[E|Es]
also containsC0+1
positive arithmetic expressions.
Sample query:
?- count_pos([1,2,3,0,-1,-2], C).
C = 3
; false.
关于list - Prolog:计算列表中的正元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423535/