# max element of list in prolog

• 03-16-2013
std10093
max element of list in prolog
Maybe I should post at Tech board?

I want to find the max element of a list, in Prolog.

Here is my code (see comments)
Code:

```maxList([], M). maxList([X|L], M):-         M is X,                 maxList2(L, M). maxList2([], M):-writeln(M). /* HERE I HAVE THE CORRECT RESULT! */ /* But the output is going to remain set at the 1st element of the  list, no matter what! */ maxList2([X|L], M):-         X > M,                 M1 is X,                         maxList2(L, M1). maxList2([X|L], M):-         X =< M,                 maxList2(L, M).```
Any ideas ? :)
• 03-17-2013
std10093
I started from scratch and finally I came up with this code
Code:

```maxOfTwo(X, Y, X) :-         X >= Y. maxOfTwo(X, Y, Y) :-         X < Y. maxL([X], X). maxL([H | T], X) :-         maxL(T, I),                 maxOfTwo(H, I, X).```
• 03-18-2013
brewbuck
I think your second version is pretty good. It's been a while since I wrote any Prolog though.
• 03-19-2013
std10093
The first was not ok. When backtracking, the result could not be maintained. I finished with the program way before the deadline, so I wrote another predicate (an iterative method - the max is actually the maxOfTwo I have above) for finding max element of a list in prolog. Here it is:
Code:

```maxlist1([X | List], Max):-       maxlist2(List, X, Max). maxlist2([], Max, Max). maxlist2([X | List], SoFarMax, Max):-       max(X, soFarMax, NewSoFarMax),             maxlist2(List, NewSoFarMax, Max). /***** and the max, instead of the maxOfTwo I have above, could be written like an if-else statement, with the cut we learned at this course ********/ max(X, Y, X):- X >= Y, !. max(X, Y, Y).```
Where did you have to write prolog brewbuck? I mean where prolog was helpful for you? :)
• 03-22-2013
brewbuck
Quote:

Originally Posted by std10093
Where did you have to write prolog brewbuck? I mean where prolog was helpful for you? :)

I used it in a couple of applications as a sort of "reverse parser" to generate all strings produced by a given grammar. It's been a while!
• 03-23-2013
std10093
Pretty interesting... :)