# find maximun in a list of lists

You did not specify a casee for `Max_List <= Value`. But you do not need to branch for the two cases. Prolog’s `is/2` [swi-doc] can evaluate an expression with `max(…, …)``, indeed:

``````?- M is max(1,2).
M = 2.
``````

We thus can calculate the maximum of the `Max_list` and `Value`:

``````matrix_max([], Max, Max).
matrix_max([Head | Rest], Value, Max) :-
MaxCur is max(Max_List, Value),
matrix_max(Rest, MaxCur, Max).``````

The `matrix_max/2` predicate can not use `0` as initial accumulator, since the values can all be smaller than zero. You should first call `my_max/2` on the first row:

``````matrix_max([Head | Rest], Max) :-
matrix_max(Rest, M, Max).``````

You furthermore need to cover the case where the list is empty, so the first clause.

In a similar way you can simplify `my_max/3`:

``````my_max([X|L], M) :-
my_max(L, X, M).

my_max([], R, R).
my_max([X|Xs], WK, R):-
V is max(X, WK),
my_max(Xs, V, R).``````

You can implement both `my_max` and `matrix_max` as a “fold pattern” with `foldl/4`:

``````max2(X1, X2, M) :-
M is max(X1, X2).

my_max([X|Xs], M) :-
my_max(Xs, X, M).

my_max(Xs, M0, M) :-
foldl(max2, Xs, M0, M).

matrix_max([R|Rs], M) :-
my_max(R, RM),
foldl(my_max, Rs, RM, M).``````