gpt4 book ai didi

Prolog - 如果满足条件则添加到总计

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

我正在尝试编写一个执行此操作的 Prolog 函数:

Takes three parameters: a name, a course list, and an integer. The integer should be equal to the number of projects in the list that include the name.

编辑

我已经稍微清理了我的代码:

studentCount(Name, [], 0).
studentCount(Name, [Project|MoreProjects], Sum) :-
nameInProject(Name, Project),
studentCount(Name, MoreProjects, Sum),
NewSum is Sum + 1.
studentCount(Name, [Project|MoreProjects], Sum) :-
not(nameInProject(Name, Project)),
studentCount(Name, MoreProjects, Sum).

nameInProject(Name, Name1+Name2+_) :-
Name == Name1;
Name == Name2.

它将 N 绑定(bind)到列表的长度,但是,每次我调用它时:

?- studentCount(x,[x+y+1,a+b+2,c+x+3],N)
N = 3.

由于原子 x 在两个项目中可见,它应该将 N 绑定(bind)到 2。不确定我应该在哪里寻找错误。

最佳答案

也许你应该使用以下内容:

studentCount(Name, [], 0).
studentCount(Name, [Project|MoreProjects], NewSum) :-
nameInProject(Name, Project),
studentCount(Name, MoreProjects, Sum),
NewSum is Sum + 1.
studentCount(Name, [Project|MoreProjects], Sum) :-
not(nameInProject(Name, Project)),
studentCount(Name, MoreProjects, Sum).

% checks if name is in the project
nameInProject(Name, Name1+Name2+_) :-
Name == Name1;
Name == Name2.

因为你用来递增 Sum 的 NewSum 是你最后需要得到的。


编辑:我现在没有 prolog 解释器,但你甚至可以尝试以下操作:

studentCount(Name, [], 0).
studentCount(Name, [Project|MoreProjects], NewSum) :-
nameInProject(Name, Project),
studentCount(Name, MoreProjects, Sum),
NewSum is Sum + 1;
studentCount(Name, MoreProjects, NewSum).

% checks if name is in the project
nameInProject(Name, Name1+Name2+_) :-
Name == Name1;
Name == Name2.

关于Prolog - 如果满足条件则添加到总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43338300/

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