Monday, 6 June 2016

Haskell: Group list of tuples by using second element

Given a list of tuples like this:

dic = [(1,"aa"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg"),(1,"bb")]

Group hem by using second element of every tuple.


ListUtil.hs

{-# LANGUAGE TransformListComp #-}

import GHC.Exts
import Data.List
import Data.Function (on)

process :: [(Integer, String)] -> [(String, [Integer])]
process list = [ (the y, x) | (x, y) <- list, then  group by y using groupWith ]


*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> process [(1,"aa"),(1,"cc"),(2,"aa"),(3,"ff"),(3,"gg"),(1,"bb")]
[("aa",[1,2]),("bb",[1]),("cc",[1]),("ff",[3]),("gg",[3])]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment