# Shortening a string in Haskell with a condition

by Kappa123   Last Updated March 14, 2019 20:26 PM

I've got the following function:

``````munch :: String -> String
munch = take 9 . chomp
``````

Which will take the longest amount of repeated characters from a string and one will limit this to 9, e.g. if given the string "aaaaabbbcc" , the answer would be "aaaaa"

I need to define a function, runs, which will do a similiar thing but it will put the string into separate lists, e.g. if the given string is `"aaaaabbbccc"` , the answer would be `["aaaaa","bbb","cc"]`, and I need to use the munch function to do this.

The condition of 9 characters applies too, so if the given string is `"aaaaaaaaaa"` , the answer would be `["aaaaaaaaa","a"]`

I've not actually got any implementation apart from something that I found which does pretty much does the same thing without the limit of 9 characters:

``````runs :: String -> String
runs x = group x
``````

I thought of 2 ways of doing this, but I have no clue on the actual implementation, with one being to run the munch function for however many unique characters there are, i.e if there is an x amount of a , b , c in the given string, it would run 3 times, and then put those lists together into one list.

Another way that I thought of is to use guards. If the number of any single character in the given string is 9 or less, then just use the group function, otherwise, shorten it down using munch, or something like that.

Is anyone able to tell me if the two ideas I mentioned would work at all or suggest an alternative and how to get started? I'm a bit lost.

Tags :

A quick google gives you exactly what you're looking for.

If it works consider upvoting their answer as I only copied a link

Lorenzo
March 14, 2019 20:19 PM

here is another approach

define a split function to break arrays at fixed size chunks

``````splitn :: Int -> [a] -> [[a]]
splitn _ [] = []
splitn n x = take n x : (splitn n \$ drop n x)
``````

now you can write your function as

``````runs =  concatMap (splitn 9) . group
``````
karakfa
March 14, 2019 20:25 PM

## Related Questions

Updated December 24, 2016 07:41 AM

Updated February 24, 2017 17:26 PM

Updated September 22, 2017 12:26 PM

Updated January 11, 2018 00:26 AM

Updated March 19, 2019 11:26 AM