Predsort/3 like msort/2

纵饮孤独 提交于 2019-12-19 18:28:14

问题


I would like to know is it possible to use predsort/3 without losing duplicate values? If not, that how should I sort this list of terms?

Current sort function:

compareSecond(Delta, n(_, A, _), n(_, B, _)):-
        compare(Delta, A, B).

Result:

predsort(compareSecond, [n(3, 1, 5), n(0, 0, 0), n(8, 0, 9)], X).
X = [n(0, 0, 0), n(3, 1, 5)].

You see, that term n(8,0,9) is gone and that's not what I need.


回答1:


predsort will remove duplicates, but it leaves it to the comparison predicate to define which elements are duplicates. Adapt your compareSecond predicate to also compare the first and third arguments to the functors it receives, if the second argument compares equal.

Alternatively, switch to msort:

?- maplist(swap_1_2, [n(3, 1, 5), n(0, 0, 0), n(8, 0, 9)], Swapped),
|    msort(Swapped, SortedSwapped),
|    maplist(swap_1_2, Sorted, SortedSwapped).
% snip
Sorted = [n(0, 0, 0), n(8, 0, 9), n(3, 1, 5)] .

where the definition of swap_1_2 is left as an exercise to the reader.




回答2:


If you're not bothered about further sorting the duplicates, this simple addition prevents them from being removed.

compareSecond(Delta, n(_, A, _), n(_, B, _)):-
    A == B;
    compare(Delta, A, B).


来源:https://stackoverflow.com/questions/8247032/predsort-3-like-msort-2

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