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>import Data.Bifunctor (first) |
|||
⚫ | |||
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 ((0, _), xs) = ((1, c), xs) |
|||
go c ((n, 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" |
|||
<> " |
<> "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 |