问题
I have a set of companies in rank order. I want my rule to check if the companies in a specified list are in rank order, and for the rule to recur until all companies in the list have been checked.
I currently have the following:
isOrder([]).
isOrder([COM1,COM2|T]) :-
rank(COM1,D), rank(COM2,E),
D<E,
print("in order"),
isOrder([COM2|T]).
However, this does not seem to work. Sometimes, the recursion goes on forever without ending, and sometimes the recursion doesn't work at all. This is when I vary the code to try and get the correct answer.
Can anybody help me? I have just started Prolog and my understanding of it is severely limited. Any help would be greatly appreciated.
回答1:
The problem is that your program has no case for a one-element list: the first case handles the empty list, while the second only matches a list with two or more elements.
You'll need to add a clause
isOrder([_]).
回答2:
In Prolog it's important to have the right "base" case for recursion, as well as getting the rule for the recursion itself right.
Here I think you want to change the base case from isOrder([ ]) to isOrder([_]), or maybe to have both of these.
The first clause you have now looks like it will return true for an empty list, which I guess does no harm. But the second clause can never reduce a nonempty list to an empty one. It only applies to a list that has at least two items (companies), and reduces such a case to a list that has at least one item.
So, add another clause isOrder([_]), which says you succeed if the list only has one item, and let us know how it works!
来源:https://stackoverflow.com/questions/4640656/how-do-i-make-a-recursive-list-that-checks-company-rankings