top of page
Dhruv Badaya

Write a Prolog program maxlist (L, Max) to find the greatest number Max in the list L.

Let's look at the code first.

% Base case: the maximum of a single-element list is that element itself
maxlist([X], X).


% Recursive case: the maximum of a list is the maximum between the head and the maximum of the tail
maxlist([Head|Tail], Max) :-
    maxlist(Tail, TailMax),  % Find the maximum of the tail
    Max is max(Head, TailMax).  % Max is the greater of Head and TailMax

% Helper predicate to find the max between two numbers
max(X, Y, X) :- X >= Y.
max(X, Y, Y) :- X < Y.

Now, let us look at the explanation for this code.


1. Base Case:

   maxlist([X], X).

If the list has only one element, then that element is the maximum.


2. Recursive Case:

   maxlist([Head|Tail], Max) :-
       maxlist(Tail, TailMax),
       Max is max(Head, TailMax).

This clause handles the case where the list has more than one element:

- It first finds the maximum of the tail (`TailMax`).

- Then it compares the head of the list (`Head`) with `TailMax` to determine the overall maximum (`Max`).


3. Helper Predicate:

   max(X, Y, X) :- X >= Y.
   max(X, Y, Y) :- X < Y.

This helper predicate `max/3` determines the maximum of two numbers. If `X` is greater than or equal to `Y`, it returns `X`; otherwise, it returns `Y`.


Usage Example

To use this program, you can query Prolog with a list to find its maximum:


?- maxlist([3, 1, 4, 1, 5, 9, 2, 6], Max).
Max = 9.

This query will result in `Max = 9`, which is the greatest number in the list `[3, 1, 4, 1, 5, 9, 2, 6]`.

400 views0 comments

Kommentarer


bottom of page