Pack the same elements into a list inside a list.

github logo ・1 min read

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]
    ]
twitter logo DISCUSS (3)
markdown guide
 

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
 

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

 
Classic DEV Post from Jan 25

What is your "Coder/Language Fit"

Anton profile image
Born into being.