Run-length encoding: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Added a variant expressed in terms of span.)
(→‎Haskell In terms of group: Tidied. Pruned out one import, added output.)
Line 2,431: Line 2,431:
===In terms of group===
===In terms of group===
<lang haskell>import Data.List (group)
<lang haskell>import Data.List (group)
import Control.Arrow ((&&&))


-- Datatypes
-- Datatypes
type Encoded = [(Int, Char)] -- An encoded String with form [(times, char), ...]
type Encoded = [(Int, Char)] -- An encoded String with form [(times, char), ...]

type Decoded = String
type Decoded = String


-- Takes a decoded string and returns an encoded list of tuples
-- Takes a decoded string and returns an encoded list of tuples
rlencode :: Decoded -> Encoded
rlencode :: Decoded -> Encoded
rlencode = map (length &&& head) . group
rlencode = fmap ((,) <$> length <*> head) . group


-- Takes an encoded list of tuples and returns the associated decoded String
-- Takes an encoded list of tuples and returns the associated decoded String
Line 2,447: Line 2,447:
main :: IO ()
main :: IO ()
main = do
main = do
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
-- Get input
-- Output encoded and decoded versions of input
putStr "String to encode: "
encoded = rlencode input
input <- getLine
-- Output encoded and decoded versions of input
let encoded = rlencode input
decoded = rldecode encoded
decoded = rldecode encoded
putStrLn $ "Encoded: " ++ show encoded ++ "\nDecoded: " ++ show decoded</lang>
putStrLn $ "Encoded: " <> show encoded <> "\nDecoded: " <> show decoded</lang>
{{Out}}
<pre>Encoded: [(12,'W'),(1,'B'),(12,'W'),(3,'B'),(24,'W'),(1,'B'),(14,'W')]
Decoded: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</pre>


Or:
Or: