我正在尝试在 Prolog 中为我的家庭作业编写一个家谱程序。这是代码的一部分。
/** a sample fact **/
parents(someone, someoneelse, child).
/** are M and F parents of the children in the given list? **/
parents(M,F,[]) :- parents(M,F,_).
parents(M,F,[First|Rest]) :- parents(M,F,First), parents(M,F,Rest).
/** are M and F parents? **/
parents(M,F) :- parents(M,F,_).
当我使用与事实匹配的查询时,上面的代码有效。
[trace] 25 ?- parents(someone,someoneelse).
Call: (6) parents(someone, someoneelse) ? creep
Call: (7) parents(someone, someoneelse, _G586) ? creep
Exit: (7) parents(someone, someoneelse, child) ? creep
Exit: (6) parents(someone, someoneelse) ? creep
true
.
但是当我尝试这个时:
[trace] 26 ?- parents(aa, bb).
Call: (6) parents(aa, bb) ? creep
Call: (7) parents(aa, bb, _G541) ? creep
Call: (8) parents(aa, bb, _G541) ? creep
Call: (9) parents(aa, bb, _G541) ? creep
Call: (10) parents(aa, bb, _G541) ?
...
它不起作用,它进入一个无限循环。我在这里做错了什么?
编辑:我已经改变了代码:
/** a sample fact **/
parents(someone, someoneelse, child).
/** are M and F parents of the children in the given list? **/
parents(M,F,[]).
parents(M,F,[First|Rest]) :- parents(M,F,First), parents(M,F,Rest).
/** are M and F parents? **/
parents(M,F) :- parents(M,F,A), not(A=[]).
现在我得到的是:
[trace] 3 ?- parents(a,b).
Call: (6) parents(a, b) ? creep
Call: (7) parents(a, b, _G514) ? creep
Exit: (7) parents(a, b, []) ? creep
^ Call: (7) not([]=[]) ? creep
^ Fail: (7) not(user: ([]=[])) ? creep
Redo: (7) parents(a, b, _G514) ? creep
Call: (8) parents(a, b, _G508) ? creep
Exit: (8) parents(a, b, []) ? creep
Call: (8) parents(a, b, _G509) ? creep
Exit: (8) parents(a, b, []) ? creep
Exit: (7) parents(a, b, [[]]) ? creep
^ Call: (7) not([[]]=[]) ? creep
^ Exit: (7) not(user: ([[]]=[])) ? creep
Exit: (6) parents(a, b) ? creep
true
.
我不明白为什么它现在失败后要重做。有任何想法吗?