Reputation: 3358
I'm trying to compare the elements of a list
of integer
to see if they are ordered (or not). I'm using Amzi!
I gave a few attempts, but nothing works... :(
ordered([X]).
ordered([N|[N1|L]]) :- N <= N1, ordered([N1|L]).
ordered_([X]).
ordered_([Head,Head1|Tail]) :- Head <= Head1, ordered_([Head1|Tail]).
Both return no
if this list is entered:
ordered([1,2,3,4]).
ordered_([1,2,3,4]).
I understand that I need to compare the head
with the head of the tail
.
Upvotes: 2
Views: 8897
Reputation: 2483
More efficient alternative to most upvoted solution, comparing three instead of appending the bigger element back to the list
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).
Upvotes: 0
Reputation: 60004
a compact alternative:
ordered(L) :- \+ ( append(_,[A,B|_], L), A > B ).
Upvotes: 2
Reputation: 74197
Doesn't seem like it should be any more complex than
ordered( [] ) .
ordered( [_] ) .
ordered( [X,Y|Z] ) :- X =< Y , ordered( [Y|Z] ) .
Arithmetic comparison predicates are covered here: http://www.amzi.com/manuals/amzi/pro/ref_math.htm#MathematicalComparisons
Use @=</2
or compare/3
to check the ordering of things in the standard order of terms: http://www.amzi.com/manuals/amzi/pro/ref_manipulating_terms.htm#StandardOrder
Upvotes: 5