Monday 6 June 2016

Haskell: Group list of names using their length


ListUtil.hs
{-# LANGUAGE TransformListComp #-}

import GHC.Exts

processInfo list = [ (the len, name) | name <- list, let len = length name, then group by len using groupWith ]

Prelude> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> processInfo ["Hari", "Krishna", "PTR", "Nayan", "Rama", "Gopi", "Sudheer"]
[(3,["PTR"]),(4,["Hari","Rama","Gopi"]),(5,["Nayan"]),(7,["Krishna","Sudheer"])]
*Main> 


Rerun ListUtil.hs by removing the keyword ‘the’, you will get following output.
*Main> processInfo ["Hari", "Krishna", "PTR", "Nayan", "Rama", "Gopi", "Sudheer"]
[([3],["PTR"]),([4,4,4],["Hari","Rama","Gopi"]),([5],["Nayan"]),([7,7],["Krishna","Sudheer"])]


‘the’ function to change the type of length of names from a list to its original numeric type.
*Main> :t the
the :: Eq a => [a] -> a
*Main> 
*Main> the [1, 1, 1]
1
*Main> the ["abc", "abc", "abc"]
"abc"


Previous                                                 Next                                                 Home

No comments:

Post a Comment