Reputation: 71
I have a list and each element of the list has five components, so the list would be something like [[1,3,4,5,6], [2,4,5,15,16],...]. I want to find the maximum of the third component of all elements in the list. I am using the following routine but it does not work:
maxList([_,_,_,_,_],Max).
maxList([_,_,A,_,_|F],Max):- A>=Max, Max1=A, maxList(F,Max1).
maxList([_,_,A,_,_|F],Max):- A<Max, Max1=Max, maxList(F,Max1).
Can anyone help? Thank you very much.
Upvotes: 1
Views: 141
Reputation: 692
Here is an improved version (does not create any choice-point and the recursion is terminal). For this it uses an auxiliary predicate with an accumulator. NB: only the 3 first elements of the lists are "matched".
maxList([[_,_,X|_]|L], Max) :-
maxList(L, X, Max).
maxList([], Max, Max).
maxList([[_,_,X|_]|L], Max, Max2):-
Max1 is max(X, Max),
maxList(L, Max1, Max2).
Upvotes: 2
Reputation: 5675
You can try
maxList(L,Max) :-
select([_,_,Max,_,_], L, L1), \+ (member([_,_,M,_,_], L1), M > Max).
CapelliC gives the template of the solution in a previous thread.
Upvotes: 1
Reputation: 726569
Your code does not treat the first parameter as a list of lists - rather, it treats it as a list of five elements.
Here is how you can fix this:
maxList([[_,_,Max,_,_]], Max). /* List of one element */
maxList([[_,_,A,_,_]|F], Max):- maxList(F, B), Max is max(A, B).
This solution uses built-in max/2
.
Upvotes: 3