2017-04-11 168 views
2

我試圖寫一個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上。不知道我到底在哪裏uld尋找錯誤。

回答

3

也許你應該使用下列內容:

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. 

當你用它來增加總和就是你需要得到的到底是什麼NewSum。


編輯: 我沒有一個序言解釋,但現在,你甚至可以嘗試以下方法:

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.