开发者

Prolog query to find largest element in database?

开发者 https://www.devze.com 2023-01-22 08:10 出处:网络
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?

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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号