I’m working my way through “Prolog For Artificial Intelligence” by Ivan Bratko, and exercise 3.17 is to write a maxlist(L, M)
that succeeds when M
is the largest number in the list L
.
My attempt at this was:
maxlist([H|T], Max) :-
maxlist(T, H, Max).
maxlist([], Max, Max).
maxlist([H|T], CurrentMax, Max) :-
(
CurrentMax > H
-> maxlist(T, CurrentMax, Max)
;
maxlist(T, H, Max)
).
The author’s solution was:
maxlist([N], N). maxlist([N1,N2|T], Max) :- maxlist([N2|T], MaxTail), max(N1, MaxTail, Max).
My code is longer, and not as easy to read, but his code gave a choice point.
Anyone have any comments on either piece of code? In particular, is there anything to choose his over mine or vice versa?
Thanks