如何在元组列表中使用Groupby?
我该如何按第二个元素进行分组:
[(3,2),(17,2),(50,3),(64,3)]
要获得类似的东西:
[[(3,2),(17,2)],[(50,3),(64,3)]]
我实际上是Haskell的新来者……似乎正在爱上它。希望您能帮助我找到一种有效的方法。
How can I group this list by second element of tuples:
[(3,2),(17,2),(50,3),(64,3)]
to get something like:
[[(3,2),(17,2)],[(50,3),(64,3)]]
I'm actually a newcomer to Haskell...and seems to be falling in love with it. Hope you would help me find an efficient way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您已经确定要
data.list.groupby
。此功能的类型是因此,它需要二进制谓词,即确定如何分组元素的等效关系。您想在一对的第二学期中按平等分组元素,因此您想要
snd
是一个内置函数,获得了一对的第二个元素。顺便说一句,这种模式“将函数应用于两个参数,然后将二进制函数应用于结果”是非常常见的,尤其是在调用
data.list
函数时,因此代码> data.function 提供 。怪异的签名,但用例就是我们想要的。
因此,您所需的
groupby
可以写为注意,
groupby
仅找到连续等于元素。您没有说明您是否想要连续的均等元素或 all 等于元素,但是如果您想要后者,那么我不相信Haskellbase
提供该功能您当然可以自己递归地写。It sounds like you've already identified that you want
Data.List.groupBy
. The type of this function isSo it takes a binary predicate, i.e. an equivalence relation determining how to group elements. You want to group elements by equality on the second term of a pair, so you want
Where
snd
is a built-in function that gets the second element of a pair.Incidentally, this pattern of "apply a function to two arguments and then apply a binary function to the results" is very common, especially when calling
Data.List
functions, soData.Function
provideson
.Weird signature, but the use case is just what we want.
So your desired
groupBy
can be written asNote that
groupBy
only finds consecutive equal elements. You didn't indicate whether you wanted consecutive equal elements or all equal elements, but if you want the latter, then I don't believe Haskellbase
provides that function, though you could certainly write it recursively yourself.