DEV Community

Anton
Anton

Posted on

Pack the same elements into a list inside a list.

Again a challenge from 99 Elm problems

Convert a list to a list of lists where repeated elements of the source list are packed into sublists. Elements that are not repeated should be placed in a one element sublist.

pack [1,1,1,2,3,3,3,4,4,4,4,5,6,6] ==
    [ [1,1,1]
    , [2]
    , [3, 3, 3]
    , [4, 4, 4, 4]
    , [5]
    , [6, 6]
    ]

Top comments (3)

Collapse
 
antonrich profile image
Anton

For now I have this. Can you guess what's wrong with this code?

pack : List a -> List (List a)
pack list =
    List.foldr pusher [] list

pusher : a -> List b -> List (List b)
pusher y ys =
    if List.isEmpty ys then
        y :: ys
    else
        if y == List.head <| List.head ys then
            y :: List.head ys
        else
            [y] :: ys
Collapse
 
idanarye profile image
Idan Arye

Should [1, 2, 1] be converted to [[1], [2], [1]] or to [[1, 1], [2]]?

Collapse
 
antonrich profile image
Anton

To [[1], [2], [1]]