News for hackers. Stuff that matters.

homic

Re:Fun with a Functional Programming Interview Question on Sunday February 07, 2021 @01:06AM (#26053043)
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)