Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell group elements in the list and concatenate different adjacent element together

The group function in Data.List can group the same element in a list
Input:

import Data.List(group)
group "mississippi time"

Output:

["m","i","ss","i","ss","i","pp","i"," ","t","i","m","e"]

How to modify the group function to group the different adjacent elements together?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expect:

["mi","ss","i","ss","i","pp","i time"]

>Solution :

What about this?

 map concat $ groupBy (\x y -> all ((== 1) . length) [x, y]) $ group "mississippi time"

I guess the lambda can be shortened somehow.

I guess (== 1) . length could be named isSingleton.

And, it could be implemented as null . tail to save some parenthesis, fwiw:

 map concat $ groupBy (\x y -> all (null . tail) [x, y]) $ group "mississippi time"

With some more playing, you can even get rid of variables x and y and write it in point-free style, provided you write an alternative of all for pairs,

all' p (a, b) = p a && p b
map concat $ groupBy (curry $ all' (null . tail)) $ group "mississippi time"

but this is likely less readable.


You need import Data.List (groupBy) too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading