How do I make a recursive list that checks company rankings?

泪湿孤枕 提交于 2019-12-25 04:35:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!