excercise3-F21
1. Write a Haskell function greater lt x that returns all integers in lt that are greater than x. Assume that
lt contains at least one element.
E.g. ?-greater [3,6,2,7,4,6,1,9] 4 = [6,7,6,9] //6, 7, 6, and 9 in the list are greater than 4
greater [y] x
| y > x = [y]
| otherwise = []
greater (y:ys) x
| y > x = y: greater ys x
| otherwise = greater ys x
2. Write a Haskell program deletefirst x k lt that deletes the first k occurrences of x from list lt. If lt
contains less than k occurrences of x, then deletes all occurrences of x from list lt.
E.g. deletefirst 1 3 [2,1,3,1,4,1,5,1,6] = [2,3,4,5,1,6] //delete the first 3 occurrences of 1
deletefirst 1 3 [1,3,1,4] = [3,4] //1 occurs only twice, so delete all occurrences of 1
deletefirst x k [] = []
deletefirst x 0 lt = lt
deletefirst x k (y:ys)
| x==y = deletefirst x (k-1) ys
| otherwise = y:deletefirst x k ys
3. Write a Haskell function slice i j lt that returns a list containing elements between the ith and the jth
element of list lt. Assume that i < j and the length of lt is greater than j.
E.g. > slice 3 6 [2,3,5,7,9,8,1,4]
[5,7,9,8] //returns elements between the 3rd and 6th element of the list
—j=1
slice 1 1 (x:xs) = [x]
—-i=1: the first j elements of x:xs are the first element + the first (j-1) elements of xs
slice 1 j (x:xs) = x: slice 1 (j-1) xs
—-i>1: elements between the ith and the jth element of x:xs are elements between the (i-1)th and
—-the (j-1)th element of xs
slice i j (x:xs) = slice (i-1) (j-1) xs
4. Write a Haskell function delete_last x lt to delete the last occurrence of x in list lt. If lt does not
contain x, then return lt.
E.g. delete_last 2 [1,2,3,2,4,2,5] = [1,2,3,2,4,5] // remove the last occurrence of 2
Solution 1:
delete_last x [] = []
delete_last x (y:ys)
|elem x ys = y:delete_last x ys
|x ==y = ys // x does not appear in ys
|otherwise = y:ys //x does not appear in y:ys
Solution 2:
delete_last x lt = reverse (delete_first x (reverse lt))
delete_first x [] = []
delete_first x (y:ys)
|x == y = ys
|otherwise = y:delete_first x ys