Find max integer in a list in prolog

后端 未结 2 350
醉酒成梦
醉酒成梦 2020-12-21 16:53

I am trying to find the max number in a list. I know there are several solutions available online but I feel the best way to learn is to implement on my own.

I wrote

2条回答
  •  误落风尘
    2020-12-21 17:05

    You aren't ensuring that Res is instantiated. You don't neccesary need a helper predicate to do that. You could make the recursive call before the check if Res is bigger than H where Res is the biggest integer of T.

    You can use ->, but you don't have to. But if you don't, a little bit more backtracking would be involved.

    If you try to stay more on your route with recursion after the check, you'll need a helper predicate, as lurker has suggested.

    Edit: Since the answer is accepted now, here are the three suggestions implemented:

    max1([H|T], Y):-  % with the -> operator, call first
        max1(T,X),
        (H > X ->
         H = Y;
         Y = X).
    max1([X],X).
    
    
    max2([H|T], Y):-  % without the -> operator, call first (this might be very inefficient)
        max2(T,Y),
        H < Y.
    max2([H|T], H):-
        max2(T,Y),
        H >= Y.
    max2([X],X).
    
    
    max3([H|T], Y) :- max_(T,H,Y).            % with helper predicate
    max_([H|T],HighestNow,Highest):-          % call after the test
        (H > HighestNow -> max_(T,H, Highest)
         ;
         max_(T,HighestNow,Highest)).
    max_([],X,X).
    

提交回复
热议问题