Problem 11 Solutions

Adapts the takeWhile/dropWhile solution from Problem 9.

type RleCode a
    = Run Int a
    | Single a


takeWhile : (a -> Bool) -> List a -> List a
takeWhile predicate xs =
    case xs of
        [] ->
            []

        hd :: tl ->
            if (predicate hd) then
                hd :: takeWhile predicate tl
            else
                []


dropWhile : (a -> Bool) -> List a -> List a
dropWhile predicate list =
    case list of
        [] ->
            []

        hd :: tl ->
            if (predicate hd) then
                dropWhile predicate tl
            else
                list


rleEncode : List a -> List (RleCode a)
rleEncode list =
    case list of
        [] ->
            []

        hd :: tl ->
            let
                remainder =
                    dropWhile (\x -> x == hd) tl

                front =
                    takeWhile (\x -> x == hd) list
            in
                case List.length front of
                    0 ->
                        rleEncode remainder

                    1 ->
                        Single hd :: rleEncode remainder

                    n ->
                        Run n hd :: rleEncode remainder

Back to Problem

results matching ""

    No results matching ""