Haskell:在元组列表中组合整数 [英] Haskell: Combine integers in a list of tuples

查看:115
本文介绍了Haskell:在元组列表中组合整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从这里得到:

[(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)

其中someFunc是我还需要弄清楚的一点并执行。我相信它应该利用foldr,map和/或intercalate来实现我的目标。任何想法?

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?

推荐答案

这应该是:

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

这篇关于Haskell:在元组列表中组合整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆