Prolog:计算列表中的正元素
Prolog: Count positive elems in list
我想计算列表中的正元素 (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+1
用于 C 作为输入变量。
有什么办法可以修复我的代码吗?
以下代码使用clpfd on swi-prolog, so don't expect it to run as-is on 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).
让我们看一下在"arrow":-
方向的通俗易懂的从句,即"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
contains C
positive arithmetic expressions
and if some arithmetic expression E
is not positive
then conclude that [E|Es]
also contains C
positive arithmetic expressions.
count_pos([E|Es], C) :- E #> 0, C #= C0+1, count_pos(Es, C0).
If list Es
contains C0
positive arithmetic expressions
and if some arithmetic expression E
is positive
then conclude that [E|Es]
also contains C0+1
positive arithmetic expressions.
示例查询:
?- count_pos([1,2,3,0,-1,-2], C).
C = 3
; false.
我想计算列表中的正元素 (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+1
用于 C 作为输入变量。
有什么办法可以修复我的代码吗?
以下代码使用clpfd on swi-prolog, so don't expect it to run as-is on 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).
让我们看一下在"arrow":-
方向的通俗易懂的从句,即"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.
示例查询:
?- count_pos([1,2,3,0,-1,-2], C).
C = 3
; false.