-
Notifications
You must be signed in to change notification settings - Fork 0
/
02StartingOut.hs
54 lines (45 loc) · 2 KB
/
02StartingOut.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
-- Find the penultimate element in list l
penultimate l = last (init l)
-- Find the element at index k in list l
-- For example: "findK 2 [0,0,1,0,0,0]" returns 1
findK k l = l !! k
-- Determine if list l is a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome l = l == reverse l
{-
- Duplicate the elements in list xs, for example "duplicate [1,2,3]" would give the list [1,1,2,2,3,3]
- Hint: The "concat [l]" function flattens a list of lists into a single list.
- (You can see the function definition by typing ":t concat" into the interpreter. Perhaps try this with other variables and functions)
-
- For example: concat [[1,2,3],[3,4,5]] returns [1,2,3,3,4,5]
-}
duplicate xs = concat [[x, x] | x <- xs]
{-
- Imitate the functionality of zip
- The function "min x y" returns the lower of values x and y
- For example "ziplike [1,2,3] ['a', 'b', 'c', 'd']" returns [(1,'a'), (2, 'b'), (3, 'c')]
-}
ziplike :: [a] -> [b] -> [(a, b)]
ziplike _ [] = []
ziplike [] _ = []
ziplike (x:xs) (y:ys) = (x, y) : ziplike xs ys
-- Split a list l at element k into a tuple: The first part up to and including k, the second part after k
-- For example "splitAtIndex 3 [1,1,1,2,2,2]" returns ([1,1,1],[2,2,2])
splitAtIndex :: Int -> [a] -> ([a], [a])
splitAtIndex k l = (take k l, drop k l)
-- Drop the element at index k in list l
-- For example "dropK 3 [0,0,0,1,0,0,0]" returns [0,0,0,0,0,0]
dropK :: Int -> [a] -> [a]
dropK k l = take (k-1) l ++ drop k l
-- Extract elements between ith and kth element in list l. Including i, but not k
-- For example, "slice 3 6 [0,0,0,1,2,3,0,0,0]" returns [1,2,3]
slice :: Int -> Int -> [a] -> [a]
slice i k l = take (k-i) (drop i l)
-- Insert element x in list l at index k
-- For example, "insertElem 2 5 [0,0,0,0,0,0]" returns [0,0,0,0,0,2,0]
insertElem :: a -> Int -> [a] -> [a]
insertElem x k l = take (k-1) l ++ x:drop (k-1) l
-- Rotate list l n places left.
-- For example, "rotate 2 [1,2,3,4,5]" gives [3,4,5,1,2]
rotate :: Int -> [a] -> [a]
rotate n l = drop n l ++ take n l