Monday, 6 June 2016

Haskell: Group list of tuples by using first 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 first element of every tuple.

ListUtil.hs

{-# LANGUAGE TransformListComp #-}

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

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


Prelude> :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","cc","bb"]),(2,["aa"]),(3,["ff","gg"])]


Previous                                                 Next                                                 Home

No comments:

Post a Comment