在 haskell 中对列表的列表进行排序

发布于 2024-08-22 05:12:47 字数 497 浏览 3 评论 0原文

我完全困惑于如何编写一个函数,在给定一个集合列表的情况下,该函数返回按大小拆分为子列表的集合(并且子列表按它们包含的集合的大小排序)。

样本输入

*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]]

样本输出

*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]]]

基本上,它应该将所有相同大小的集合分组为自己的集合,然后将下一个最大大小的集合分组。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蹲在坟头点根烟 2024-08-29 05:12:48

您使用的是“集合”一词,但您的代码实际上使用了列表...因此,这是一个基于列表的解决方案(如果您想切换到实际集合,可以轻松调整):

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

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

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):

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

groupBy ((==) `on` length) $ sortBy (compare `on` length) [[0],[1,2],[3]]
-- => [[[0],[3]],[[1,2]]]
春风十里 2024-08-29 05:12:48

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

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

After importing Data.Function, Data.Ord and List, you can write this:

sortBy (comparing length) $ groupBy ((==) `on` length) $ sortBy (comparing length) theList
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文