Haskell: Combine integers in a list of tuples [duplicate]

半城伤御伤魂 提交于 2019-12-24 01:11:49

问题


I need to get from here:

[(2,"a"), (1,"a"), (1,"b"), (1,"c"), (2,"dd")]

to here:

[([1, 2], "a"), ([1], "b"), ([1], "c"), ([2], "dd")]

So far I have

combineInts listTuple = someFunc (map (\(num, str) -> ([num], str)) listTuple)

where "someFunc" is the bit I still need to figure out and implement. I believe it should utilize foldr, map, and/or intercalate to accomplish my goal. Any ideas?


回答1:


This should do:

import Data.Function (on)
import Data.List (groupBy, sort, sortBy)

out = map f . groupBy ((==) `on` snd) . sortBy (compare `on` snd) $ input
  where input = [(2,"a"),(1,"a"),(1,"b"),(1,"c"),(2,"dd")]
        f xs@(x:_) = (sort $ map fst xs, snd x)

main = print out



回答2:


You can do this using groupBy if you order the list first:

import Data.List (groupBy)
import Data.Ord (comparing)
import Data.Function (on)

map (\l@((_,c):_) -> (map fst l, c))  $ groupBy (on (==) snd) $ sortBy (comparing snd) inputList


来源:https://stackoverflow.com/questions/32769930/haskell-combine-integers-in-a-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!