LZW compression: Difference between revisions
Content deleted Content added
→{{header|Haskell}}: Replaced older liftM2 and ap with <$> ... <*> etc. Added main and GHC output. |
|||
Line 2,036:
<lang Haskell>import Data.List (elemIndex, tails)
import Data.Maybe (fromJust)
take2 :: [a] -> [[a]]▼
take2 xs = filter ((2 ==) . length) (take 2 <$> tails xs)▼
doLZW :: String -> String -> [Int]
Line 2,059 ⟶ 2,055:
(!!)
(foldl
(
▲ (\x xs -> return (liftA2 (++) head (take 1 . last) ((x !!) <$> xs))))
(return <$> a)
(take2 cs))
▲take2 :: [a] -> [[a]]
▲take2 xs = filter ((2 ==) . length) (take 2 <$> tails xs)
<lang Haskell>*Main> doLZW ['\0'..'\255'] "TOBEORNOTTOBEORTOBEORNOT"▼
[84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263]▼
main :: IO ()
*Main> undoLZW ['\0'..'\255'] [84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263]▼
main = do
"TOBEORNOTTOBEORTOBEORNOT"</lang>▼
print $
undoLZW
True</lang>▼
['\0' .. '\255']
▲
print $
((==) <*> ((.) <$> undoLZW <*> doLZW) ['\NUL' .. '\255'])
▲ "TOBEORNOTTOBEORTOBEORNOT"</lang>
{{Out}}
▲<pre>[84,79,66,69,79,82,78,79,84,256,258,260,265,259,261,263]
"TOBEORNOTTOBEORTOBEORNOT"
Other (elegant) code can be found at Haskell wiki [http://www.haskell.org/haskellwiki/Toy_compression_implementations Toy compression]
|