如何在元组列表中使用Groupby?

发布于 2025-02-03 22:16:00 字数 202 浏览 2 评论 0原文

我该如何按第二个元素进行分组:

[(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 技术交流群。

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

发布评论

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

评论(1

猥︴琐丶欲为 2025-02-10 22:16:00

听起来您已经确定要 data.list.groupby 。此功能的类型是

  groupby ::(a  - > a  - > bool) - > [a]  - > [[一个]] 
 

因此,它需要二进制谓词,即确定如何分组元素的等效关系。您想在一对的第二学期中按平等分组元素,因此您想要

groupBy (\x y -> snd x == snd y) myList

snd是一个内置函数,获得了一对的第二个元素。

顺便说一句,这种模式“将函数应用于两个参数,然后将二进制函数应用于结果”是非常常见的,尤其是在调用data.list函数时,因此代码> data.function 提供

  on ::( b  - > b  - > c) - > (a  - > b) - > a  - > a  - > c 
 

怪异的签名,但用例就是我们想要的。

 (( +)`on f)xy = fx + fy
 

因此,您所需的groupby可以写为

groupBy ((==) `on` snd)

注意,groupby仅找到连续等于元素。您没有说明您是否想要连续的均等元素或 all 等于元素,但是如果您想要后者,那么我不相信Haskell base提供该功能您当然可以自己递归地写。

It sounds like you've already identified that you want Data.List.groupBy. The type of this function is

groupBy :: (a -> a -> Bool) -> [a] -> [[a]] 

So 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

groupBy (\x y -> snd x == snd y) myList

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, so Data.Function provides on.

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c 

Weird signature, but the use case is just what we want.

((+) `on` f) x y = f x + f y

So your desired groupBy can be written as

groupBy ((==) `on` snd)

Note 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 Haskell base provides that function, though you could certainly write it recursively yourself.

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