How to group a chain into four strings?

advertisements

How can I turn a string into a lists of repeated characters with length no more than four? I made a function that reduces the length of the String to four, and I called it chop, but I need a function that separates the strings into lists of repeated characters and then use chop.

Let's call the function that does this task lsi, so that the result of lsi "aaaaaaabbb" is ["aaaa", "aaa", "bbb"]. I have tried using the following function to implement lsi, but it doesn't chop the string down to four characters.

run [] = []
run (x:xs) = (x : takeWhile (==x) xs)


import Data.List (group)

chop _ [] = []
chop n xs = take n xs : chop n (drop n xs)

lsi :: (Eq a) => [a] -> [[a]]
lsi = concatMap (chop 4) . group

I defined chop slightly differently. It simply divides a list into a list of lists, with the given maximum length for each sublist.

ghci> chop 2 "abcdefgh"
["ab","cd","ef","gh"]

After that lsi is a simple matter of composing group and concatMap with chop 4.

ghci> lsi "aaaaaabbbbbccc"
["aaaa","aa","bbbb","b","ccc"]

I suggest you Hoogle group and concatMap if you aren't familiar with them yet.