简体   繁体   English

排序haskell中的列表列表

[英]sorting lists of lists in haskell

I'm completely stumped on how to write a function that, given a list of sets returns the sets split into sublists by size (and with the sublists ordered by the size of sets they contain). 我完全不知道如何编写一个函数,给定一个集合列表返回按大小拆分为子列表的集合(以及按照它们包含的集合大小排序的子列表)。

sample input 样本输入

*Main> allSets
[[1,2],[8],[1,4,7,8],[5],[1,4],[1],[2,3],[1,2,5,8],[3,4,6,7],[1,2,3,4],[4],[5,6,7,8],[3,4],[3],[2,3,5,6],[7],[6],[2]]

sample output 样本输出

*Main> collectByLength allSets
[[[2],[6],[7],[3],[4],[1],[5],[8]],[[3,4],[2,3],[1,4],[1,2]],[[2,3,5,6],[5,6,7,8],[1,2,3,4],[3,4,6,7],[1,2,5,8],[1,4,7,8]]]

Basically, it should group all the sets of the same size into their own set,then it groups the sets of the next largest size. 基本上,它应该将所有相同大小的集合分组到它们自己的集合中,然后它将下一个最大大小的集合分组。

You're using the word "sets", but your code actually uses lists... So, here's a list-based solution (easily adaptable in case you'd like to switch to actual sets): 你正在使用“sets”这个词,但是你的代码实际上使用了列表......所以,这里是一个基于列表的解决方案(如果你想切换到实际的集合,很容易适应):

import Data.List (sortBy)
import Data.Function (on)

groupBy ((==) `on` length) $ sortBy (compare `on` length) [[0],[1,2],[3]]
-- => [[[0],[3]],[[1,2]]]

导入Data.Function,Data.Ord和List后,您可以这样写:

sortBy (comparing length) $ groupBy ((==) `on` length) $ sortBy (comparing length) theList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM