Shortening a string in Haskell with a condition

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

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 : string haskell


Answers 2


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

https://codereview.stackexchange.com/questions/158183/string-splitting-function-in-haskell

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

Lorenzo
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
karakfa
March 14, 2019 20:25 PM

Related Questions


Remove a Character Sequence From a String

Updated December 24, 2016 07:41 AM

how to construct a Map Text Text object?

Updated February 24, 2017 17:26 PM

Haskell: checking the vowels in a String

Updated September 22, 2017 12:26 PM

How do I search for some text in Haskell?

Updated January 11, 2018 00:26 AM