Solution
%% Base case: the list has one element. %% The maximum must be this element as there are no other elements %% which could be bigger. max([Max],Max). %% Two recursive clauses which compute the maximum of the tail and %% then compare the result to the head. %% First case: the head is greater than the maximum of the tail. The %% head is the maximum of the whole list. max([Head|Tail],Max) :- max(Tail,TailMax), Head > TailMax, Max = Head. %% Second case: the head is smaller or equal to the maximum of the %% tail. The maximum of the tail is the maximum of the whole list. max([Head|Tail],Max) :- max(Tail,TailMax), Head =< TailMax, Max = TailMax.
This definition is not very efficient. When asked the query
max([3,45,3,6,7,4,33,4,98],M)
, for example, Prolog
will first try to use the second clause of the definition. This
involves a recursive call for computing the maximum of the tail
[45,3,6,7,4,33,4,98]
. This yields 98, which is
greater than 3 (the head of the input list). So the test
Head > TailMax
fails. Prolog starts to backtrack
and tries the last clause, which means that it has to compute
the maximum of the tail again. You will see how to define a more
efficient version of max
in a later exercise.