user1834372
user1834372

Reputation: 135

Prolog checking if a list is in strictly decreasing sequence

I am new to Prolog and am trying to write a procedure for a strictly decreasing sequence for an assignment.

Now define a predicate isOrdered, such that 'isOrdered(Lst)' succeeds if the items in the list, Lst, are in strictly decreasing sequence. You may assume Lst contains only numbers. e.g. ?- isOrdered([11, 5, 3, 0]). true.

This is what I have so far:

isOrdered([]).
isOrdered([A|B]) :- isOrdered([B]), A > B. 

It's giving me an error that says out of local stack. Can't seem to wrap my head around this.

Upvotes: 2

Views: 977

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

When you use this list construct in Prolog

[H | T]

you are splitting the list into a head and a tail. The head is a single item (could be a list if the original list is a list of lists) and tail is the original list with the initial element removed. That's why A > B is incorrect.

You need to do something like this:

isOrdered([]).
isOrdered([_]).
isOrdered([A,B|T]) :- A > B, isOrdered([B|T]). 

Upvotes: 4

Related Questions