我在为AI课程做作业,正在编写一个Prolog程序。
我需要处理一个名字列表,并检查列表中的每个人是否属于所选择的特定国家。
我目前的代码如下:
% factsperson(bruce, australia, rhodri, bronwyn).person(rhodri, newyork, dan, mary).person(bronwyn, miami, gar, roo).person(dan, miami, george, mimi).person(mary, texas, mack, tiki).person(gar, jamaica, zid, rem).person(roo, newzealand, john, jill).person(tom, mayday, dick, mel).person(dick, newyork, harry, rin).person(mel, miami, tom, stacey).person(harry, miami, george, mimi).person(rin, texas, mack, tiki).person(tom, jamaica, zid, rem).person(stacey, newzealand, john, jill).% ruleseligible(P,C) :- person(P, C, F, M) , ! ; person(F, C, Newfather, Newmother), ! ; person(M, C, Newfather, Newmother), ! ; person(Newfather, C, Grandfather , Grandmother), ! ; person(Newmother, C, Grandfather, Grandmother).checkteam([] , C). checkteam([H|T] , C) :- eligible(H, C) , checkteam(T, C).
特别是最后两行我遇到了问题,我试图用eligible()
函数测试列表中的每个成员,然后让尾部的第一个元素成为头部并重复这个过程。
我无法找到一种方法来测试每个成员,然后如果有任何成员不符合条件就显示失败,或者如果所有成员都属于那个国家就显示真。
提前感谢。
编辑:我一直在摆弄代码,稍作了一些修改,关于结果:
?- checkteam([bruce, dan], mayday).true.
尽管bruce和dan都不来自mayday,也没有父母或祖父母来自那里。
回答:
你的eligible
谓词对我来说不太合理(可能是我误解了)。但是,如果person
定义为person(Name, Country, Father, Mother)
,那么它可以是:
eligible(Name, Country) :- person(Name, Country, _, _).eligible(Name, Country) :- person(Name, _, Father, _), person(Father, Country, _, _).eligible(Name, Country) :- person(Name, _, _, Mother), person(Mother, Country, _, _).
然后你的checkteam
仍然会给你一个警告。在变量名前加下划线可以消除它:
checkteam([], _Country).