Prolog查询以查找数据库中的最大元素? [英] Prolog query to find largest element in database?
问题描述
如果我已经定义了 Prolog 数据库中的所有数字,例如 dig(0), dig(1), ..., dig(9)
.我可以使用什么查询让 Prolog 返回最大数字——在本例中为 9?
If I have defined all the digits in a Prolog database, such as dig(0), dig(1), ..., dig(9)
. What query can I use for Prolog to return the largest digit -- in this case, 9?
我尝试了类似的东西:
?- dig(N), dig(M), N > M.
但这只是返回第一种可能性,而不是最大的数字.
But that just returns the first possibility, not the largest number.
推荐答案
虽然最短的解决方案可能是:
While the shortest solution is probably:
?- dig(Max), \+((dig(X), X > Max)).
概念上最简单的解决方案可能是:
the conceptually simplest solution might be:
?- findall(X, dig(X), Digits), max_list(Digits, Max).
但请查看 prolog 子句定义的最大值以获得更多解决方案,复杂性越来越好.
But check out Max out of values defined by prolog clauses for more solutions, with better and worse complexities.
您可以通过查阅此文件来测试这两种解决方案的速度:
You can test the speed of these two solutions by consulting this file:
:- between(1, 12345, X), assert(dig(X)), fail ; true.
:- time((findall(X, dig(X), Digits), max_list(Digits, Max))),
write('Findall max: '), write(Max), nl.
:- time((dig(Max), \+((dig(X), X > Max)))), write('\\+ max: '), write(Max), nl.
在我 5 岁的笔记本电脑上,它清楚地表明 findall
-version 如果你有例如12345 个条目在您的数据库中.
On my 5 years old laptop it clearly shows that the findall
-version is much faster if you have e.g. 12345 entries in your database.
% 37,085 inferences, 0.05 CPU in 0.06 seconds (87% CPU, 741700 Lips)
Findall max: 12345
% 76,230,375 inferences, 60.94 CPU in 72.30 seconds (84% CPU, 1250909 Lips)
\+ max: 12345
这篇关于Prolog查询以查找数据库中的最大元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!