[Haskell-cafe] Help to solve simple problem !
Eduard Sergeev
Eduard.Sergeev at gmail.com
Tue Nov 10 20:07:11 EST 2009
Aneto wrote:
>
> compress :: Eq a => [a] -> [(a, Int)]
> If you have string "AAABCCC" it transforms it to : {A, 3} {B,1} {C,3}
>
Basically you need to "group" equal elements of the list first and then
transform every group (which is a list of equal elements) to the tuple of
(first_element , the_ length_of_the_group). All necessary functions can be
found in Prelude and Data.List:
import Data.List
compress :: Eq a => [a] -> [(a, Int)]
compress xs = map (\g -> (head g, length g)) (group xs)
PS You can express it somehow nicer with arrows thought:
import Data.List
import Control.Arrow
compress :: Eq a => [a] -> [(a, Int)]
compress = map (head &&& length) <<< group
--
View this message in context: http://old.nabble.com/Help-to-solve-simple-problem-%21-tp26249028p26294356.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.
More information about the Haskell-Cafe
mailing list