Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Finding Minimum of A List



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

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

  • Divide the list as [X,Y|Tail]. Now recursively find min of [Y|Tail] and store it into MinRest, and store minimum of X and MinRest, then store it to Min.

Program (list_misc.pl)

min_of_two(X,Y,X) :- X =< Y.
min_of_two(X,Y,Y) :- X > Y.
list_min_elem([X],X).
list_min_elem([X,Y|Rest],Min) :-   list_min_elem([Y|Rest],MinRest),   min_of_two(X,MinRest,Min).

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_min_elem([8,5,3,4,7,9,6,1],Min).

Min = 1 ? 

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

Min = 4 ? 

yes
| ?- 

Explanation

  • min_of_two(X,Y,X) :- X =< Y is a helper function which checks X as same or less than Y then Min is X.

  • min_of_two(X,Y,Y) :- X > Y. It is another case where if X is greater than Y then Min is Y.

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

  • list_min_elem([X,Y|Rest],Min) :- list_min_elem([Y|Rest],MinRest), min_of_two(X,MinRest,Min). returns Min as the lowest element of the list.

    • list_min_elem([X,Y|Rest],Min) 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. Min is the result as Minimum element of the list.

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

    • min_of_two(X,MinRest,Min) compares X and MinRest and then return the Min as lowest value.

Advertisements