Problem 9

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.

Example

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]
    ]

Unit Test

import Html
import List
import Maybe


pack : List a -> List (List a)
pack xs =
    -- your implementation goes here
    [ [] ]


main : Html.Html a
main =
    Html.text
        <| case test of
            0 ->
                "Your implementation passed all tests."

            1 ->
                "Your implementation failed one test."

            x ->
                "Your implementation failed " ++ (toString x) ++ " tests."


test : Int
test =
    List.length
        <| List.filter ((==) False)
            [ pack [ 1, 1, 1, 1, 2, 5, 5, 2, 1 ] == [ [ 1, 1, 1, 1 ], [ 2 ], [ 5, 5 ], [ 2 ], [ 1 ] ]
            , pack [ 2, 1, 1, 1 ] == [ [ 2 ], [ 1, 1, 1 ] ]
            , pack [ 2, 2, 2, 1, 1, 1 ] == [ [ 2, 2, 2 ], [ 1, 1, 1 ] ]
            , pack [ 1 ] == [ [ 1 ] ]
            , pack [] == []
            , pack [ "aa", "aa", "aa" ] == [ [ "aa", "aa", "aa" ] ]
            , pack [ "aab", "b", "b", "aa" ] == [ [ "aab" ], [ "b", "b" ], [ "aa" ] ]
            ]

Hints

  1. One solution recurses using a helper function accumulating the output lists.
  2. takeWhile and dropWhile could come in handy in another recursive solution.
  3. A solution can be written using foldr. The function passed to foldr needs to return the same output as pack, namely List (List a).

Solutions

Solutions

results matching ""

    No results matching ""