本文介绍了在prolog的列表中查找最大整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在列表中查找最大数量.我知道网上有几种解决方案,但我觉得最好的学习方式是自己实施.

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.

我写了以下代码:

max([X],X).
max([H|T],Res):-
    (  H >= Res
    -> max(T,Res1), Res1 = H
    ;  max(T,Res)
    ).

谁能指出我的错误?我想不通.

Can someone point out my mistake? I am not able to figure it out.

推荐答案

您没有确保 Res 被实例化.你不需要一个辅助谓词来做到这一点.您可以在检查 Res 是否大于 H 之前进行递归调用,其中 ResT.

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.

如果您在检查后尝试通过递归更多地停留在您的路线上,您将需要一个辅助谓词,如 lurker 已建议.

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

由于现在已经接受了答案,这里是实施的三个建议:

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).

这篇关于在prolog的列表中查找最大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:02