Run-length encoding: Difference between revisions

Content added Content deleted
(→‎Haskell: Added a variant expressed as a fold.)
(→‎Haskell :: As a fold: Slight reduction – pruned out an import.)
Line 2,911: Line 2,911:


===As a fold===
===As a fold===
<lang haskell>----------------------- RUN LENGTHS ----------------------
<lang haskell>import Data.Bifunctor (first)

----------------------- RUN LENGTHS ----------------------


runLengths :: String -> [(Int, Char)]
runLengths :: String -> [(Int, Char)]
runLengths "" = []
runLengths "" = []
runLengths s =
runLengths s = uncurry (:) (foldr go ((0, ' '), []) s)
where
let go c ("", xs) = ([c], xs)
go c (cs@(x : run), xs)
go c ((0, _), xs) = ((1, c), xs)
| c == x = (c : cs, xs)
go c ((n, x), xs)
| otherwise = ([c], (length cs, x) : xs)
| c == x = ((succ n, x), xs)
| otherwise = ((1, c), (n, x) : xs)
in uncurry
(:)
( first
((,) . length <*> head)
(foldr go ("", []) s)
)


--------------------------- TEST -------------------------
--------------------------- TEST -------------------------
Line 2,933: Line 2,926:
main = do
main = do
let testString =
let testString =
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW"
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWW"
<> "WWWWWWWWWWBWWWWWWWWWWWWWW"
<> "WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
encoded = runLengths testString
encoded = runLengths testString
putStrLn $ showLengths encoded
putStrLn $ showLengths encoded
Line 2,941: Line 2,934:
------------------------- DISPLAY ------------------------
------------------------- DISPLAY ------------------------
showLengths :: [(Int, Char)] -> String
showLengths :: [(Int, Char)] -> String
showLengths [] = []
showLengths [] = []</lang>
showLengths ((n, c) : xs) = show n <> [c] <> showLengths xs</lang>
{{Out}}
{{Out}}
<pre>12W1B12W3B24W1B14W
<pre>12W1B12W3B24W1B14W