Monday 6 June 2016

Haskell: Group list of tuples by using first element, sort the second list of grouped elements

Given a list of tuples like this:

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

You have to group like below.

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


ListUtil.hs
{-# LANGUAGE TransformListComp #-}

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

process :: [(Integer, String)] -> [(Integer, [String])]
process list = [(the a, b) |  let info = [ (x, y) | (x, y) <- list, then sortWith by y ], (a, b) <- info, then group by a 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")]
[(1,["aa","bb","cc"]),(2,["aa"]),(3,["ff","gg"])]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment