3 回答
TA贡献1862条经验 获得超7个赞
这是我的解决方案:
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)
这首先通过以下方式对列表进行排序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")]
然后按相关键对列表元素进行分组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")]]
然后将分组的项目转换为元组map:
[[(1,"aa"),(1,"bb"),(1,"cc")],[(2,"aa")],[(3,"ff"),(3,"gg")]]
=> [(1,["aa","bb","cc"]), (2, ["aa"]), (3, ["ff","gg"])]`)
测试:
> myGroup dic
[(1,["aa","bb","cc"]),(2,["aa"]),(3,["ff","gg"])]
TA贡献1752条经验 获得超4个赞
尽可能重用库代码。
import Data.Map sortAndGroup assocs = fromListWith (++) [(k, [v]) | (k, v) <- assocs]
在ghci中尝试一下:
*Main> sortAndGroup [(1,"aa"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg"),(1,"bb")]fromList [(1,["bb","cc","aa"]),(2,["aa"]),(3,["gg","ff"])]
TA贡献1828条经验 获得超3个赞
您也可以使用TransformListComp扩展,例如:
Prelude> :set -XTransformListComp Prelude> import GHC.Exts (groupWith, the)Prelude GHC.Exts> let dic = [ (1, "aa"), (1, "bb"), (1, "cc") , (2, "aa"), (3, "ff"), (3, "gg")]Prelude GHC.Exts> [(the key, value) | (key, value) <- dic, then group by key using groupWith][(1,["aa","bb","cc"]),(2,["aa"]),(3,["ff","gg"])]
添加回答
举报