Predsort/3 像 msort/2 [英] Predsort/3 like msort/2

查看:8
本文介绍了Predsort/3 像 msort/2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用 predsort/3 而不会丢失重复值?如果不是,那我应该如何对这个术语列表进行排序?

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?

当前排序功能:

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

结果:

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

你看,那个术语 n(8,0,9) 已经消失了,这不是我需要的.

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

推荐答案

predsort 删除重复项,但它留给比较谓词来定义哪些元素是重复项.如果第二个参数比较相等,则调整您的 compareSecond 谓词以将第一个和第三个参数与其接收的函子进行比较.

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.

或者,切换到 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)] .

swap_1_2 的定义留给读者作为练习.

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

这篇关于Predsort/3 像 msort/2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆