3 ms·
I attempted this as a Haskell beginner. Positive it can be improved upon. runLengthEncode :: String -> [(Char, Int)] runLengthEncode [] = [] runLen
by homic 6y ago
I attempted this as a Haskell beginner. Positive it can be improved upon.
runLengthEncode :: String -> [(Char, Int)]
runLengthEncode [] = []
runLengthEncode input =
let
chFirst = head input
zipped = zip input $ chFirst : input
in
rle zipped (chFirst, 0)
where
rle :: [(Char, Char)] -> (Char, Int) -> [(Char, Int)]
rle [] (ch, count) = [(ch, count)]
rle ((ch1, ch2) : cs) (ch, count) =
if ch1 == ch2 then
rle cs (ch1, count + 1)
else
(ch2, count) : rle cs (ch1, 1)