在序言中找到列表中的最大整数 [英] Find max integer in a list in 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
之前进行递归调用,其中Res
是T
的最大整数.
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).
这篇关于在序言中找到列表中的最大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!