Haskell使用代理订单对不可订单列表进行排序

时间:2021-03-27 17:13:25

Suppose I have x :: [(n, a)] where n is a number and a is an unorderable item (is not of class Ord).

假设我有x :: [(n,a)]其中n是数字,a是不可订购的项目(不是Ord类)。

I want to sort this list by n.

我想用n对这个列表进行排序。

I cannot do sort x because a is not orderable. I can replace a by indices and then assemble the new list using !! but this seems like a poor solution.

我不能对x进行排序,因为a是不可订购的。我可以替换索引,然后使用!!组装新列表!但这似乎是一个糟糕的解决方案。

Alternatives?

备择方案?

3 个解决方案

#1


12  

Ugh. Never mind. sortBy.

啊。没关系。排序方式。

#2


5  

You want

你要

sortBy (compare `on` fst)

or something similar. You'll find on defined in module Data.Function, and sortBy in Data.List, which you'll need to import.

或类似的东西。您将在模块Data.Function中定义,并在Data.List中找到sortBy,您需要导入它。

#3


2  

Also, if you have an alternate function (e.g., call it f) from which to form an order, you can use the Data.Monoid properties of Ordering:

此外,如果您有一个替代函数(例如,调用它)来形成一个订单,您可以使用Ordering的Data.Monoid属性:

sortBy (comparing fst `mappend` comparing (f . snd))

which will use your function on the second component of the pair. If you don't need or have a second criterion on which to sort your pairs, then the sortBy (comparing fst) will be just fine (the resulting list will just have pairs with the same first component in list order).

它将在对的第二个组件上使用您的函数。如果你不需要或没有第二个标准来对你的对进行排序,那么sortBy(比较fst)就可以了(结果列表只有在列表顺序中具有相同第一个组件的对)。

#1


12  

Ugh. Never mind. sortBy.

啊。没关系。排序方式。

#2


5  

You want

你要

sortBy (compare `on` fst)

or something similar. You'll find on defined in module Data.Function, and sortBy in Data.List, which you'll need to import.

或类似的东西。您将在模块Data.Function中定义,并在Data.List中找到sortBy,您需要导入它。

#3


2  

Also, if you have an alternate function (e.g., call it f) from which to form an order, you can use the Data.Monoid properties of Ordering:

此外,如果您有一个替代函数(例如,调用它)来形成一个订单,您可以使用Ordering的Data.Monoid属性:

sortBy (comparing fst `mappend` comparing (f . snd))

which will use your function on the second component of the pair. If you don't need or have a second criterion on which to sort your pairs, then the sortBy (comparing fst) will be just fine (the resulting list will just have pairs with the same first component in list order).

它将在对的第二个组件上使用您的函数。如果你不需要或没有第二个标准来对你的对进行排序,那么sortBy(比较fst)就可以了(结果列表只有在列表顺序中具有相同第一个组件的对)。