RosettaCodeData/Task/Move-to-front-algorithm/Haskell/move-to-front-algorithm.hs

26 lines
576 B
Haskell
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
import Data.List (delete, elemIndex, mapAccumL)
import Data.Maybe (fromJust)
2015-02-20 09:02:09 -05:00
table :: String
2017-09-23 10:01:46 +02:00
table = ['a' .. 'z']
2015-02-20 09:02:09 -05:00
encode :: String -> [Int]
2017-09-23 10:01:46 +02:00
encode =
let f t s = (s : delete s t, fromJust (elemIndex s t))
in snd . mapAccumL f table
2015-02-20 09:02:09 -05:00
decode :: [Int] -> String
2017-09-23 10:01:46 +02:00
decode = snd . mapAccumL f table
2015-02-20 09:02:09 -05:00
where
2017-09-23 10:01:46 +02:00
f t i =
let s = (t !! i)
in (s : delete s t, s)
2015-02-20 09:02:09 -05:00
main :: IO ()
2017-09-23 10:01:46 +02:00
main =
mapM_ print $
(,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x)
((,) <*> (decode . snd) <$>
((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"]))