检查是否订购了清单

时间:2015-08-21 12:24:39

标签: list prolog

我正在尝试比较list integer的元素,看看它们是否有序(或不是)。我正在使用Amzi!

我做了几次尝试,但没有任何作用...... :(

ordered([X]).
ordered([N|[N1|L]]) :- N <= N1, ordered([N1|L]).

ordered_([X]).
ordered_([Head,Head1|Tail]) :- Head <= Head1, ordered_([Head1|Tail]).

如果输入此列表,则返回no

ordered([1,2,3,4]).
ordered_([1,2,3,4]).

我知道我需要将headhead of the tail进行比较。

3 个答案:

答案 0 :(得分:4)

似乎不应该比

更复杂
ordered( []      ) .
ordered( [_]     ) .
ordered( [X,Y|Z] ) :- X =< Y , ordered( [Y|Z] ) .

此处涵盖了算术比较谓词:http://www.amzi.com/manuals/amzi/pro/ref_math.htm#MathematicalComparisons

使用@=</2compare/3检查标准的术语顺序中的事物顺序:http://www.amzi.com/manuals/amzi/pro/ref_manipulating_terms.htm#StandardOrder

答案 1 :(得分:2)

紧凑的替代方案:

ordered(L) :- \+ ( append(_,[A,B|_], L), A > B ).

答案 2 :(得分:0)

对大多数建议的解决方案更有效的替代方法,比较三个而不是将较大的元素添加回列表中

is_sorted([]).
is_sorted([X, Y, Z|T]) :- X =< Y, Y =< Z, is_sorted(T).
is_sorted([X, Y|T]) :- X =< Y, is_sorted(T).