/
Problems1to10.hs
62 lines (40 loc) · 1.14 KB
/
Problems1to10.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Problems1to10 where
import Data.List (foldl')
-- Solutions for Problems 1-10
-- Problem 1
myLast :: [a] -> a
myLast = head . reverse
-- Problem 2
myButLast :: [a] -> a
myButLast = head . tail . reverse
-- Problem 3
elementAt :: Int -> [a] -> a
elementAt n = head . drop (n-1)
-- Problem 4
myLength :: [a] -> Int
myLength = foldl' (\n _ -> 1 + n) 0
-- Problem 5
reverseList :: [a] -> [a]
reverseList = foldl (flip (:)) []
-- Problem 6
isPalindrome :: Eq a => [a] -> Bool
isPalindrome xs = xs == reverse xs
-- Problem 7
data List a = Element a | List [List a]
flatten :: List a -> [a]
flatten (Element e) = [e]
flatten (List xs) = concatMap flatten xs
-- Problem 8
compress :: Eq a => [a] -> [a]
compress = map head . groupDuplicates
-- Problem 9
groupDuplicates :: Eq a => [a] -> [[a]]
groupDuplicates [] = []
groupDuplicates (x:xs) = (x:duplicates) : groupDuplicates rest
where
(duplicates, rest) = span (x==) xs
-- Problem 10
encode :: Eq a => [a] -> [(Int, a)]
encode xs = map encodeElem (groupDuplicates xs)
where
encodeElem ys = (length ys, head ys)