对列表中的 Erlang 记录进行排序?
我在 erlang 中有一条记录:
-record(myrec,
{
id = 0,
price = 0,
quantity = 0
}).
然后我有一个记录列表,我想按 id 和价格排序,按降序和升序排列,其中价格是第一个键,如果两个记录具有相同的价格,我想对它们进行排序通过 ID。
我如何为此定义乐趣?
我是 Erlang 的新手:)
谢谢, 尼斯总线
I have a record in erlang:
-record(myrec,
{
id = 0,
price = 0,
quantity = 0
}).
I then have a list of records that I want to sort by id and price, both in descending and ascending order, where price is the first key and if two records have the same price I want to sort those by id.
How can I define a fun for this?
I'm a newb at Erlang :)
thanks,
nisbus
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将产生(假设示例文件 t.erl):
This will yield (assuming example file
t.erl
):这是比迄今为止建议的解决方案更短的解决方案。首先定义您的记录:
然后让我们发明其中的 3 个:
现在我们需要一个比较函数。这是解决方案较短的地方。 Erlang 可以按照元组中出现的顺序比较术语,因此如果我们想按价格排序,然后按 id 排序,我们只需比较
{PriceA, IdA}
{PriceA, IdA}
形式的两个元组即可。 {PriceB, IdB}
:并将其插入
lists:sort/2
:顺序现在为
[B, A, C]
并且您的列表已排序。请注意,如果您想按 id 降序排序,您可以通过反转元组中的 id 来欺骗它,如下所示:
给我们
[B, C, A]
。这对读者来说并不明显,因此您最好将其记录下来或在这种情况下使用达斯汀的解决方案。这里提出的解决方案的优点是不需要嵌套。通过在比较中的任一元组中设置元素,您几乎可以根据需要比较任意数量的元素,而无需使代码变得更长。This is a shorter solution than what has been suggested so far. First define your record:
Then let's invent 3 of them:
Now we need a comparison function. This is where the solution is shorter. Erlang can compare terms of a tuple in the order they appear, so if we want to sort by price, then by id, we just have to compare two tuples of the form
{PriceA, IdA} < {PriceB, IdB}
:And plug it in
lists:sort/2
:The order is now
[B, A, C]
and your list is sorted.Note that if you wanted to sort by descending id instead, You could trick it by reversing the ids in the tuples as follows:
Giving us
[B, C, A]
. This is not obvious to the reader, so you'd better document it or use Dustin's solution in this case. The advantage of the solution presented here is that there is no nesting required. By setting elements in either tuple in the comparison, you can pretty much compare as many of them as you want without making the code that much longer.首先,您弄清楚如何比较您的记录:
然后,您只需使用普通的
lists:sort
函数和比较函数即可获得您想要的内容(这是一个eunit
我对上述内容进行了测试,以确保我做了一些有意义的事情):First, you figure out how to compare your records:
Then, you just use the normal
lists:sort
function with your comparison function to get what you want (this is aneunit
test of the above I ran to make sure I did something that made sense):