问题
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