list - Prolog:计算列表中的正元素

标签 list prolog clpfd visual-prolog

我想计算列表中的正元素(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 用作输入变量。

有什么办法可以修复我的代码吗?

最佳答案

以下代码使用 ,所以不要期望它在 按原样运行:-(
不过,我希望它对你有用!

:- 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".

  1. count_pos([], 0).

    The number of positive arithmetic expressions contained in the empty list [] is zero.

  2. 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.

  3. 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.

Sample query:

?- count_pos([1,2,3,0,-1,-2], C).
   C = 3
;  false.

关于list - Prolog:计算列表中的正元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423535/

相关文章:

prolog - 在Prolog中重构纠结的循环规则

prolog - 序言中的setof

prolog - 制定效果公理

prolog - 限制整数在集合中

prolog - 如何确定矩阵的所有给定坐标都已连接?

javascript - 来自数据库的 Django 动态下拉列表

java - 获取进入的地理围栏的ID

prolog - 键入 Y 组合器

Matlab 独特的细胞组合

Python 转换查询输出