Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Finding Maximum of A List



This operation is used to find the maximum element from a list. We will define a predicate, list_max_elem(List, Max), then this will find Max element from the list and return.

  • If there is only one element, then it will be the max element.

  • Divide the list as [X,Y|Tail]. Now recursively find max of [Y|Tail] and store it into MaxRest, and store maximum of X and MaxRest, then store it to Max.

Program (list_misc.pl)

max_of_two(X,Y,X) :- X >= Y.
max_of_two(X,Y,Y) :- X < Y.
list_max_elem([X],X).
list_max_elem([X,Y|Rest],Max) :-   list_max_elem([Y|Rest],MaxRest),   max_of_two(X,MaxRest,Max).

Output

| ?- consult('D:/TP Prolog/Sample Codes/list_misc.pl').
compiling D:/TP Prolog/Sample Codes/list_misc.pl for byte code...
D:/TP Prolog/Sample Codes/list_misc.pl compiled, 3 lines read - 1086 bytes written, 6 ms

yes
| ?- list_max_elem([8,5,3,4,7,9,6,1],Max).

Max = 9 ? 

yes
| ?- list_max_elem([5,12,69,112,48,4],Max).

Max = 112 ? 

yes
| ?- 

Explanation

  • max_of_two(X,Y,X) :- X >= Y is a helper function which checks X as greater than or same as Y then MAX is X.

  • max_of_two(X,Y,Y) :- X < Y. It is another case where if X is less than Y then MAX is Y.

  • list_max_elem([X],X). Maximum of one element List is the only item of the List.

  • list_max_elem([X,Y|Rest],Max) :- list_max_elem([Y|Rest],MaxRest), max_of_two(X,MaxRest,Max). returns Max as the highest element of the list.

    • list_max_elem([X,Y|Rest],Max) is to divide the first list where X, Y represents the first two elements of the list and Rest represents the tail of the list. MAX is the result as maximum element of the list.

    • list_max_elem([Y|Rest],MaxRest) makes a recursive call to compare the list without head X and get the next highest value as MaxRest.

    • max_of_two(X,MaxRest,Max) compares X and MaxRest and then return the Max as highest value.

Advertisements