Prolog: predicate for maximum without battery

Is it possible to create a predicate max/2without a drive, so that max(List, Max)is true if and only if it Maxis the maximum value List(list of integers)?

+6
source share
2 answers

Yes, you can calculate the maximum after the recursive step. How:

max([M],M).          % the maximum of a list with one element is that element.
max([H|T],M) :-
    max(T,M1),       % first calculate the maximum of the tail.
    M is max(H,M1).  % then calculate the real maximum as the max of
                     % head an the maximum of the tail.

, , . , , Prolog (TCO), . TCO , .

@Lurker , is , : . , Prolog clp(fd):

:- use_module(library(clpfd)).

max([M],M).          % the maximum of a list with one element is that element.
max([H|T],M) :-
    max(T,M1),       % first calculate the maximum of the tail.
    M #= max(H,M1).  % then calculate the real maximum as the max of
                     % head an the maximum of the tail.

:

?- max([A,B,C],M),A=2,B=3,C=1.
A = 2,
B = M, M = 3,
C = 1 ;
false.

, max/2, A, B C, M=3.

+3

/2, CLP (FD) (# =)/2 . , , , .

, (CAS). Jekejeke Minlog 0.9.2, CAS Prolog.

eval_keys/2 min_key/2, . , , . :

Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.3.25-3-gc3a87c2)
Copyright (c) 1990-2016 University of Amsterdam, VU Amsterdam

?- eval_keys([(1+3)-foo,2-bar],L).
L = [4-foo,2-bar]

, :

?- min_key([4-foo,2-bar],X).
X = bar

, , . . foo:

?- eval_keys([(sqrt(98428513)+sqrt(101596577))-foo,sqrt(400025090)-bar],L).
L = [20000.62724016424-foo, 20000.627240164245-bar].

?- min_key([20000.62724016424-foo, 20000.627240164245-bar], X).
X = foo.

CLP (FD) , . , CAS . , bar:

Jekejeke Prolog 2, Runtime Library 1.2.2
(c) 1985-2017, XLOG Technologies GmbH, Switzerland

?- eval_keys([(sqrt(98428513)+sqrt(101596577))-foo,sqrt(400025090)-bar],L).
L = [radical(0,[98428513-1,101596577-1])-foo,
   radical(0,[400025090-1])-bar]

?- min_key([radical(0,[98428513-1,101596577-1])-foo,
   radical(0,[400025090-1])-bar],X).
X = bar

, , . , , , :

?- use_module(library(decimal/multi)).
% 7 consults and 0 unloads in 319 ms.
Yes

?- X is mp(sqrt(98428513)+sqrt(101596577), 32).
X = 0d20000.627240164244658958331341095

?- X is mp(sqrt(400025090), 32).
X = 0d20000.627240164244408966171597261

CAS . , Prolog Swinnerton-Dyer , .

:

% :- use_module(library(groebner/generic)). /* to enable CAS */

eval_keys([X-A|L], [Y-A|R]) :- Y is X, eval_keys(L, R).
eval_keys([], []).

min_key([X-A|L], B) :- min_key(L, X, A, B).

min_key([X-A|L], Y, _, B) :- X < Y, !, min_key(L, X, A, B).
min_key([_|L], X, A, B) :- min_key(L, X, A, B).
min_key([], _, A, A).
0

Source: https://habr.com/ru/post/1017171/


All Articles