Simple haskell problem ! Help please

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Simple haskell problem ! Help please

Denis Firsov
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 !
Reply | Threaded
Open this post in threaded view
|

Simple haskell problem ! Help please

jfredett
Here are some hints to consider:

1. There are two ways to think about this -- pattern matching on a list,
    or higher-order functions
2. The former will require thinking about several cases,
        a. What is a "compressed" empty list?
        b. How many elements do we need to look at at once?
        c. What happens if the first and the next element are the same?
        d. What if they're different?
3. Higher order functions over the list might be easier, consider the
    `takeWhile` and `dropWhile` functions, as well as the `group`  
function,
    there are several ways to use these functions to solve the problem.


HTH

/Joe

On Nov 7, 2009, at 5:01 PM, Denis Firsov 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 !
> _______________________________________________
> Beginners mailing list
> [hidden email]
> http://www.haskell.org/mailman/listinfo/beginners

Reply | Threaded
Open this post in threaded view
|

Re: Simple haskell problem ! Help please

Tim Attwood
In reply to this post by Denis Firsov
> 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 !

This is straightforward with a list comprehension and the group function.

import Data.List

compress s = [(head g, length g) | g <- group s]