-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathH99_prob-09-12.hs
33 lines (28 loc) · 914 Bytes
/
H99_prob-09-12.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
-- 9
split :: [a] -> [[a]]
split [] = []
split [x] = [[x]]
split (x:xs) = [x]:(split xs)
merge :: Eq a => [[a]] -> [[a]]
merge [] = []
merge [xs] = [xs]
merge (xs:xss)
| head xs == head (head xss) = merge ((xs ++ (head xss)):(tail xss))
| otherwise = xs:(merge xss)
pack :: Eq a => [a] -> [[a]]
pack xs = merge (split xs)
-- 10. Run-length encoding
encode :: Eq a => [a] -> [(Int, a)]
encode xs = [( length x, head x) | x <- pack xs]
-- 11
data ListItem a = Single a | Multiple Int a
deriving (Show)
encodeModified :: Eq a => [a] -> [ListItem a]
encodeModified xs = [ y | x <- pack xs, let y = if length x > 1
then Multiple (length x) (head x)
else Single (head x) ]
-- 12
decodeModified :: Eq a => [ListItem a] -> [a]
decodeModified [] = []
decodeModified ((Single x):xs) = (x:decodeModified xs)
decodeModified ((Multiple n x):xs) = (replicate n x) ++ (decodeModified xs)