-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path1to10.hs
78 lines (52 loc) · 1.53 KB
/
1to10.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
---- Problem 1
-- Finds the last element of a list
myLast :: [a] -> a
-- For empty list, return an error
myLast [] = undefined
-- If list has one element, return it
myLast [last] = last
-- Recursively search for the last element
myLast (_:restOfTheList) = myLast restOfTheList
---- Problem 2
-- Finds the second last element of a list
myButLast :: [a] -> a
myButLast [] = undefined
myButLast [_] = undefined
myButLast [x, _] = x
myButLast (_:restOfTheList) = myButLast restOfTheList
---- Problem 3
-- Finds the k-th element of a list
elementAt :: [a] -> Int -> a
elementAt list index = list !! (index - 1)
---- Problem 4
-- Finds the number of elements in a list
myLength :: [a] -> Int
myLength = foldr (\_ acc -> acc + 1) 0
---- Problem 5
-- Reverses a list.
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = myReverse xs ++ [x]
---- Problem 6
-- Checks if a list is a palindrome.
isPalindrome :: Eq a => [a] -> Bool
isPalindrome l = l == reverse l
---- Problem 7
data NestedList a = Elem a | List [NestedList a]
deriving Show
flatten :: NestedList a -> [a]
flatten (Elem el) = [el]
flatten (List nested) = concatMap flatten nested
---- Problem 8
compress :: Eq a => [a] -> [a]
compress [] = []
compress [e] = [e]
compress (x:xs) = x : compress (dropWhile (== x) xs)
---- Problem 9
pack :: Eq a => [a] -> [[a]]
pack [] = []
pack l@(x:xs) = takeWhile (== x) l : pack (dropWhile (== x) xs)
---- Problem 10
encode :: Eq a => [a] -> [(Int, a)]
encode = map encodePackage . pack
where encodePackage l = (length l, head l)