如何使用Haskell将列表中的类似项目分组? [英] How to group similar items in a list using Haskell?
问题描述
$ $ $ $ $ $ $ $ c $ dic = [(1,aa),(1, (3,fg),(3,gg),(1,bb)]
如何将 dic 的项目分组,导致列表 grp 其中,
grp = [(1,[aa,bb,cc]),(2,[aa]), [ff,gg])]
我实际上是Haskell的新手。 。并且似乎正在爱上它..
在 Data.List 中使用 group 或 groupBy 将列表中的相似项目分组。
我为此编写了一个低效率的函数,但由于需要处理一个非常大的编码字符串列表,因此导致内存失败。希望你能帮助我找到更有效的方法。
这是我的解决方案:
import Data.Function(on)
import Data.List(sortBy,groupBy)
import Data.Ord(比较)
myGroup ::(等式a,等式a)=> [(a,b)] - > [(a,[b])]
myGroup = map(\ l - >(fst。head $ l,map snd l))。 groupBy((==)``fst)
。 sortBy(比较fst)
首先使用 sortBy
:
[(1,aa),(1,cc), ,aa),(3,ff),(3,gg),(1,bb)]
=> (1,bb),(1,cc),(2,aa),(3,ff),(3,gg)]
然后通过相关键将列表元素分组为 groupBy $ c $ (1,aa),(1,bb),(1,cc ),(2,aa),(3,ff),(3,gg)]
=> [[(1, AA),(1, BB),(1, CC)],[(2-, AA)],[(3, FF),(3, gg)]]
然后通过 map将分组项转换为元组
:
[[(1,aa),(1,bb), (1,cc)],[(2,aa)],[(3,ff),(3,gg)]]
=> (2,[aa]),(3,[ff,gg])]`)
测试:
> myGroup dic
[(1,[aa,bb,cc]),(2,[aa]),(3,[ff,gg])]
Given a list of tuples like this:
dic = [(1,"aa"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg"),(1,"bb")]
How to group items of dic resulting in a list grp where,
grp = [(1,["aa","bb","cc"]), (2, ["aa"]), (3, ["ff","gg"])]
I'm actually a newcomer to Haskell...and seems to be falling in love with it..
Using group or groupBy in Data.List will only group similar adjacent items in a list.
I wrote an inefficient function for this, but it results in memory failures as I need to process a very large coded string list. Hope you would help me find a more efficient way.
Here's my solution:
import Data.Function (on)
import Data.List (sortBy, groupBy)
import Data.Ord (comparing)
myGroup :: (Eq a, Ord a) => [(a, b)] -> [(a, [b])]
myGroup = map (\l -> (fst . head $ l, map snd l)) . groupBy ((==) `on` fst)
. sortBy (comparing fst)
This works by first sorting the list with sortBy
:
[(1,"aa"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg"),(1,"bb")]
=> [(1,"aa"),(1,"bb"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg")]
then grouping the list elements by the associated key with groupBy
:
[(1,"aa"),(1,"bb"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg")]
=> [[(1,"aa"),(1,"bb"),(1,"cc")],[(2,"aa")],[(3,"ff"),(3,"gg")]]
and then transforming the grouped items to tuples with map
:
[[(1,"aa"),(1,"bb"),(1,"cc")],[(2,"aa")],[(3,"ff"),(3,"gg")]]
=> [(1,["aa","bb","cc"]), (2, ["aa"]), (3, ["ff","gg"])]`)
Testing:
> myGroup dic
[(1,["aa","bb","cc"]),(2,["aa"]),(3,["ff","gg"])]
这篇关于如何使用Haskell将列表中的类似项目分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!