在 Prolog 中寻找最年长的人 [英] Finding the oldest person in Prolog
本文介绍了在 Prolog 中寻找最年长的人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据一些事实,我必须找到使用 Prolog 的最年长的人.例如:
Based on some facts, I have to find the oldest person using Prolog. For example:
age(john, 10).
age(mary, 15).
age(rose, 75).
age(jack, 49).
age(carl, 17).
age(lucy, 66).
控制台输出应该是:
?- oldest(rose).
True.
?- oldest(X).
X = rose.
我的代码如下,但不起作用:
My code is as follows, but it's not working:
oldest(P) :- age(P, X) , age(_, Y) , X >= Y.
我找不到错误,但我想这与回溯有关.有人可以帮我吗?我是 Prolog 的新手.
I can't find the error, but I guess it's something related to backtrack. Could someone help me, please? I'm new to Prolog.
推荐答案
正确的应该是
oldest(P) :- age(P, X) , \+ (age(_, Y) , Y > X).
当然,收益率上升了...
that yields rose, of course...
(\+)/1
读作 not(Goal),意思是如果目标没有解决方案就失败".
(\+)/1
read as not(Goal), and means 'fail if there are no solutions to Goal'.
编辑在 SWI-Prolog,库(aggregate) 可以做到这一点,还有更多......
edit in SWI-Prolog, library(aggregate) can do this, and much more...
oldest(P) :- aggregate(max(A,Pers), age(Pers,A), max(_,P)).
这篇关于在 Prolog 中寻找最年长的人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文