Run-length encoding: Difference between revisions

→‎Haskell :: As a fold: Slight reduction – pruned out an import.
(→‎Haskell: Added a variant expressed as a fold.)
(→‎Haskell :: As a fold: Slight reduction – pruned out an import.)
Line 2,911:
 
===As a fold===
<lang haskell>----------------------- RUN LENGTHS ----------------------
<lang haskell>import Data.Bifunctor (first)
 
----------------------- RUN LENGTHS ----------------------
 
runLengths :: String -> [(Int, Char)]
runLengths "" = []
runLengths s = uncurry (:) (foldr go ((0, ' '), []) s)
where
let go c ("", xs) = ([c], xs)
go c (cs@(x0, :_), runxs) = ((1, c), xs)
|go c ==((n, x = (c : cs), xs)
| c |== otherwisex = ([c], (lengthsucc csn, x) :, xs)
| otherwise = ((1, c), (n, x) : xs)
in uncurry
(:)
( first
((,) . length <*> head)
(foldr go ("", []) s)
)
 
--------------------------- TEST -------------------------
Line 2,933 ⟶ 2,926:
main = do
let testString =
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW"
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWW"
<> "WWWWWWWWWWBWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
encoded = runLengths testString
putStrLn $ showLengths encoded
Line 2,941 ⟶ 2,934:
------------------------- DISPLAY ------------------------
showLengths :: [(Int, Char)] -> String
showLengths [] = []</lang>
showLengths ((n, c) : xs) = show n <> [c] <> showLengths xs</lang>
{{Out}}
<pre>12W1B12W3B24W1B14W
9,655

edits