【发布时间】:2018-04-24 08:01:45
【问题描述】:
大家好,这是我的第一篇文章,所以如果您对如何提问有任何建议,我会全力以赴。等等我的问题我正在尝试使用递归对数字列表进行排序,我有一个my_max/2 谓词返回列表的最大值,所以在返回之后我从列表中选择该值,然后将其添加到我的排序中列表。然后我用新列表递归。
我的问题是谓词似乎可以工作并找到正确的列表,但是当谓词退出时,它会将所有列表恢复到原始状态,基本上撤消了谓词所做的所有工作。我认为这与 Prolog 如何回溯有关?
%finds the max of a list, if the list is empty return int_min
my_max([],-2147483647).
my_max(L,M):-select(M,L,Rest), \+ (member(E,Rest),E>M).
%calls the my_max predicate store it in X, combines x and sorted and appends
%it to sorted2,then it takes X out of unsorted and creates Unsorted2 then
%recurse with unsorted2 and sorted2 should stop and output when unsorted is
%empty or []
my_sort([],S).
%my_sort([],S):-write(S). for test
my_sort(Unsorted,Sorted):-
my_max(Unsorted,X),
append(Sorted,[X],Sorted2),
select(X,Unsorted,Unsorted2),
my_sort(Unsorted2,Sorted2).
我添加了 write 只是为了表明它对列表进行了排序。输出应该是S=[3,2,1,1]。
【问题讨论】:
-
我不了解 Prolog,但您的代码对我来说毫无意义。
my_sort([], S).不是声明对空列表进行排序会给出任意结果S?