由 prolog 子句定义的最大值 [英] Max out of values defined by prolog clauses

查看:37
本文介绍了由 prolog 子句定义的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 Prolog 中遍历列表以找到最大值,但是如果每件事都是一个单独的子句怎么办?例如,如果我有一堆猫科动物和它们的年龄,我将如何找到最老的小猫?

I know how to iterate over lists in Prolog to find the maximum, but what if each thing is a separate clause? For example if I had a bunch of felines and their ages, how would I find the oldest kitty?

cat(sassy, 5).
cat(misty, 3).
cat(princess, 2).

我的第一个想法是嗯,最老的猫是没有老猫的猫".但我真的不能很好地翻译成序言.

My first thought was "hmm, the oldest cat is the one for which no older exists". But I couldn't really translate that well to prolog.

oldest(X) :- cat(X, AgeX), cat(Y, AgeY), X \= Y, \+ AgeX < AgeY, print(Y).

这仍然错误地匹配misty".这样做的正确方法是什么?有什么方法可以更直接地迭代年龄以选择最大值?

This still errorenously matches "misty". What's the proper way to do this? Is there some way to more directly just iterate over the ages to choose max?

推荐答案

如果一只猫是一只猫并且没有比它更老的猫,那么它就是最老的猫.让我们在 Prolog 中写:

A cat is the oldest if it's a cat and there is not a cat older than it. Let's write that in Prolog:

oldest(X):- cat(X, _), not( thereAreOlders(X)), !.
thereAreOlders(X):- cat(X, N), cat(C, M), C\=X, M > N.

如果您咨询:

?- oldest(X).
X = sassy.

这篇关于由 prolog 子句定义的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆