-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path99 Haskell Problems
More file actions
71 lines (53 loc) · 2.25 KB
/
99 Haskell Problems
File metadata and controls
71 lines (53 loc) · 2.25 KB
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
--Problem 1 : Find the last element of a list.
myLast [] = error "No end for empty lists!"
myLast (x:xs) = if xs==[] then x else myLast xs
--Problem 2 : Find the last but one element of a list.
myButLast [] = error "No end for empty lists!"
myButLast (x:xs) = if length xs==1 then x else myButLast xs
--Problem 3 : Find the K'th element of a list. The first element in the list is number 1.
elementAt :: [a]->Int->a
elementAt [] _ = error "No elements in empty lists!"
elementAt a 1 = head a
elementAt (x:xs) k = if k > length (x:xs) then error "index out of bounds!" else elementAt xs (k-1)
--Problem 4 : Find the number of elements of a list.
myLength [] = 0
myLength [x] = 1
myLength (x:xs) = 1 + myLength xs
--Problem 5 : Reverse a list.
myReverse [] = []
myReverse (x:xs) = myReverse xs ++ [x]
--Problem 6 : Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).
isPalindrome a
| a == myReverse a = True
|otherwise = False
--Problem 8 : (**) Eliminate consecutive duplicates of list elements.
compress [] = []
compress [x] = [x]
compress (x:y:xs) = if (x==y) then compress (y:xs) else [x] ++ compress (y:xs)
--Problem 10 : Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.
--Quizz FS17 Asignment 3
pad2 :: Char -> String -> String
pad2 _ "" = ""
pad2 c (x:xs) = if (xs == []) then x:pad2 c xs else x:c:c:pad2 c xs
--Problem 14 : Duplicate the elements of a list.
dupli [] = []
dupli [x] = [x,x]
dupli (x:xs) = [x,x] ++ dupli xs
--Problem 15 : Replicate the elements of a list a given number of times.
repli a 0 = []
repli a 1 = a
repli "" _ = ""
repli (x:xs) k = helper x k ++ repli xs k
helper :: Char -> Int -> [Char]
helper x 0 = []
helper x k = [x]++helper x (k-1)
--Problem 16: Drop every N'th element from a list.
dropEvery list count = helper' list count count
where helper' [] _ _ = []
helper' (x:xs) count 1 = helper' xs count count
helper' (x:xs) count n = x : (helper' xs count (n - 1))
--Problem 17 : Split a list into two parts; the length of the first part is given.
--Problem 19 : Rotate a list N places to the left.
rotate [] _ = []
rotate a 0 = a
rotate (x:xs) n = rotate (xs ++ [x]) (n-1)