< 99 Elm Problems < Problem 11

Solution 1: Recursive version

runLengthEncode list =
    case list of
        [] -> []
        [ x ] -> [ Single x ]
        x :: xs ->
            case runLengthEncode xs of
                [] -> []
                Single x' :: xs' ->
                    if x' == x then
                        Multiple 2 x' :: xs'
                    else
                        Single x :: Single x' :: xs'
                Multiple n x' :: xs' ->
                    if x' == x then
                        Multiple (n + 1) x' :: xs'
                    else
                        Single x :: Multiple n x' :: xs'
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.