cicero866
cicero866

Reputation: 175

Write a predicate which determines if a list is in ascending order

I'm given the following predicates:

q8([]):-
q8([X]):-
q8([H|T]):-

which need to provide the following output

q8([2, 5, 8, 8, 8, 9]).
true.
q8([8, 5, 2, 8, 9]).
false.

My attempt was :

q8([]):-true.
q8([X]):-true.
q8([H|T]):- H<T, q8(T).

However this fails, because it attempts to unify the tail of my list to q8([X]) which only allows for one element. I'm not quite sure how to get around this.

To make it more clear, if you run q8([2,5,8,8,8,9]). I get an error because [5,8,8,8,9] can't unify with X. It never gets to the third defined q8 predicate.

I'm doing practice problems for my final, so you guys aren't helping with homework! lol

Upvotes: 0

Views: 171

Answers (1)

user27815
user27815

Reputation: 4797

q8([]):-true.
q8([_X]):-true.
q8([H1,H2|T]):- H1=<H2, q8([H2|T]).

For the third clause you need to look at the first two elements in the list, you then need to use less than or equal, and finally you need to recurse keeping the second element you took off.

Upvotes: 1

Related Questions