How would I write a two clause recursive definition to find the maximum value in a list. So far I have written this:
max(L,M):-
max([H|T],M):-
max(T,H,M).
max([],M,M).
max([H|T],Y,M):-
H =< Y,
max(T,Y,M).
max([H|T],Y,M):-
H > Y,
max(T,H,M).
This doesn't work, it says there is a syntax error which I can't quite see, and I know it isn't two clause either. Anyone know how I could simplify it to make it two clause?
Goal:
list([3,9,4,5],M)
Output:
M=9
Here is a solution for max in lists of lists
As you, I use the 'max' name for the predicate. This implementation don't rely in any built-in predicate:
DOMAINS
PREDICATES
CLAUSES
GOAL
I think the code below will solve the problem:
The syntax error results from the fact that the first two clauses have no body.
To answer your question, observe that the maximum of a list can be defined inductively as follows:
Thus,
This code uses
max/2
(SWI-Prolog, GNU-Prolog). Note that most or all Prolog implementations will have a built-in functionmax_list/2
(S, G), so there is actually no need to define it yourself.Edit: Bakore notes that a tail recursive implementation may be more efficient. You can do this by defining a predicate
max_list/3
which takes an additional argumentC
, namely the largest value seen so far.