Two clause definition to find the maximum number o

2019-06-19 16:30发布

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?

标签: prolog
8条回答
forever°为你锁心
2楼-- · 2019-06-19 17:22

This one works for sure

l:-listing.
m(L,X):-aku2(L,0,X).
aku2([],B,B).
aku2([G|O],Maks,C):-maks(Maks,G,Maks1),aku2(O,Maks1,C).
maks(A,B,C):-A>B, C is A.
maks(A,B,C):-A=<B, C is B.
查看更多
Rolldiameter
3楼-- · 2019-06-19 17:27

I know this question is old, but here's an answer using the if-then-else construct:

maxmember([X],X).
maxmember([H|T],Max) :- maxmember(T, M),(H>M -> Max is H ; Max is M).
查看更多
登录 后发表回答