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

时间:2017-04-11 06:29:43

标签: prolog

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

  

采用三个参数:名称,课程列表和整数。整数应该等于列表中包含名称的项目数。

修改

我已经清理了一下我的代码:

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绑定到列表的长度,但每次我都这样说:

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

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

1 个答案:

答案 0 :(得分:4)

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

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.