[Haskell-cafe] Help to solve simple problem !

Ezra Lalonde ezra.lalonde at gmail.com
Tue Nov 10 17:10:47 EST 2009

The following program should work:

toList :: (Eq a) => [a] -> [[a]]
toList [] = []
toList x = start : toList end
    where (start, end) = span (==(head x)) x

toTuple :: [a] -> (a, Int)
toTuple x = (head x, length x)

compress :: Eq a => [a] -> [(a, Int)]
compress x = map toTuple $ toList x

The important thing to understand here, is the "span" function from the
Prelude, and apply it recursively. 
*Main> span (=='A') "AAABCC"
*Main> span (=='h') "hhhaskell"

I've used a function "toList" to separate each part of the string into a
separate element of a list:
*Main> toList "AAABCC"
*Main> toList "EEEZZZRRAAAA!!"

>From there, "toTuple" takes the first letter of the string, and puts it with
its length in a tuple:
*Main> toTuple "EEE"
*Main> toTuple "EEEEE"

Because of how it's defined, we also get the following:
*Main> toTuple "Ezra"

But that won't matter if we only use it after "toList", as in "compress".

Also, I've used your type signature for my solution, not your example
output; if you want it to be displayed like that, you'll have to write your
own function for printing.

This solution is probably not optimal, but it's a start.

Hope that helps,

Aneto wrote:
> Hi ! I am beginner in Haskell and have problems with this problem:
> compress :: Eq a => [a] -> [(a, Int)]
> If you have string "AAABCCC" it transforms it to : {A, 3} {B,1} {C,3}
> Could you help me with it ?
> Thank you in advance !

View this message in context: http://old.nabble.com/Help-to-solve-simple-problem-%21-tp26249028p26292205.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

More information about the Haskell-Cafe mailing list