gsach
gsach

Reputation: 5775

Group consecutive elements of specific value in Haskell

I have a list of numbers in haskell and I want to perform the following transformation:

To make the requirement clear I am posting an example:

Input: [1,2,3,1,1,1,2,3,4,2,1]

Expected Output: [[1] , 2 , 3 , [1,1,1] , 2 , 3 , 4 , 2 , [1]]

Important Notice: The elements that are not equal to 1 are not added in a sublist

I have found some workarounds to make it work, but I need to find an elegant solution that does not traverse the elements of the list more than once.

Any ideas?

Upvotes: 0

Views: 1081

Answers (1)

Nazarii Bardiuk
Nazarii Bardiuk

Reputation: 4342

You need a group function

>> import Data.List
>> group [1,2,3,1,1,1,2,3,4,2,1]
>> [[1],[2],[3],[1,1,1],[2],[3],[4],[2],[1]]

note that every item is a list because values in list should have the same type. Thats why your example [[1], 2, ..] is impossible in Haskell


If you want to form groups of 1s and the rest then you could use groupBy

>> import Data.List
>> groupBy (\a -> \b -> a == b && a == 1 || a /= 1 && b /= 1) [1,2,3,1,1,1,2,3,4,2,1]
>> [[1],[2,3],[1,1,1],[2,3,4,2],[1]]

Upvotes: 6

Related Questions