gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:42:31 25 4
gpt4 key购买 nike

我想计算列表中的正元素(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com