mymax([], 'list_is_empty').
mymax([Head | []], Max) :- (Max >= Head).
mymax([Head | List], Max) :- (Max > Head), mymax(List,Max).
这似乎可以正确处理 mymax([1,5,3], 5) 等查询,但无法 自行找到最大值并给出以下错误:
ERROR: >/2: Arguments are not sufficiently instantiated
我有点明白为什么会这样,虽然我无法用语言表达。 这个问题可以解决吗?还是我的算法完全不正确?
最佳答案
该错误是由于与 Head 比较时 Max 仍未绑定(bind)而导致的。
你可以这样简化:
mymax([Max], Max).
mymax([Head | List], Max) :-
mymax(List, MaxList),
( Head > MaxList -> Max = Head ; Max = MaxList ).
编辑
我试图尽量减少对代码的修改,但是,正如 @mat 指出的那样,这只适用于表达式列表,例如数字。然后就可以写了
1 ?- mymax([4+1, 3+3], N).
N = 3+3
如果您不确定列表的域(即其元素的类型),最好使用 term comparison运算符:
( Head @> MaxList -> ... )
但现在:
?- mymax([4+1, 3+3], N).
N = 4+1
关于Prolog 列表中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838827/