Prolog query to find largest element in database?

心不动则不痛 提交于 2019-12-25 04:42:33

问题


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?

I tried something like:

?- dig(N), dig(M), N > M.

But that just returns the first possibility, not the largest number.


回答1:


To find out the largest number you should write an appropriate query, namely one that:

  • Instantiate a digit

  • Checks whether that digit is the largest (i.e. no other digit is larger)

So you might want to write something like:

largest(N):-
    dig(N),
    not((
        dig(M),
        M > N
    )).



回答2:


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).

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.

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


来源:https://stackoverflow.com/questions/4052794/prolog-query-to-find-largest-element-in-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!