Search code examples
listfunctionhaskellstack

Convert a list of things into a list of sublists


I want to write a function that converts a list of things into a list of sublists, each containing elements of the same value, which when concatenated together give the same list.

So runs [1,2,2,1,3,3,3,2,2,1,1,4] becomes [[1],[2,2],[1],[3,3,3],[2,2],[1,1],[4]]

How do I solve this problem in Haskell?


Solution

  • This function already exists, this is group :: Eq a => [a] -> [[a]]:

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