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