G6021: Comparative Programming
Extra Haskell exercises: Lists
Write Haskell functions for the following questions. Avoid using built-in functions in your answer (you may however use append ++, if needed).
Lists
1. Find the last element of a list.
2. Find the penultimate element of a list.
3. Write functions to find the largest element and the smallest element in a list. Write a third function that will compute both with one pass over the list.
4. Write a function that will remove adjacent duplications in a list. For example [1, 3, 3, 2, 2, 2, 1] becomes [1, 3, 2, 1], and ¡°aaaabbbbbcccc¡± becomes ¡°abc¡±.
5. Write a function that duplicates each element of a list. For example: [1,2,3] becomes [1,1,2,2,3,3].
6. Write a variant of the previous function that will duplicate each element of a list n times. For example:
> duplicaten [1,2,3] 3
[1,1,1,2,2,2,3,3,3]
> duplicaten “ah” 4
“aaaahhhh”
7. Write a function to drop each nth element of a list.
> dropNth [1,2,3,4,5,6] 2
[1,3,5]
> dropNth [1,2,3,4,5,6] 3
[1,2,4,5]
8. We can represent the coins (and notes) of a currency by recording the values in a list: [200,100,50,20,10,5,2,1] gives the main coins in use in the UK, where the values are in pence.
Write a function that takes an amount and a list of available coins/notes, and returns quantities of each needed to make that amount. For example:
> change 48 [50,20,10,5,2,1]
[0,2,0,1,1,1]
This says: two 20p coins, one 5p coin, one 2p, and one 1p will make 48p.
9. In Haskell, you can access the nth element of a list using the infix function from the standard library: !!. For example we have:
1
> [1,2,3,4,5] !! 3
4
Note that indexing starts from 0. Write your own version of !!. Write two versions: one using currying and one that does not. Generate an error if the element does not exist in the list. What are the types of your functions?
10. Write a function to rotate the elements of a list one place to the left. For example, [1, 2, 3, 4, 5] would become [2, 3, 4, 5, 1].
11. Write a function to rotate the elements of a list one place to the right. For example, [1, 2, 3, 4, 5] would become [5, 1, 2, 3, 4].
12. Write a function to split a list at a given position, for example:
> split [1,2,3,4] 3
([1,2,3],[4])
> split [1,2,3,4,5] 1
([1],[2,3,4,5])
13. Using split write a function to rotate a list by n places to the right. > rotn [1,2,3,4,5] 2
[4,5,1,2,3]
14. Write a function to compute how many lower case letters there are in a string. Try writing this function using list comprehensions.
15. Write a function to compute how many upper case letters there are in a string. Try writing this function using list comprehensions.
16. Try some variants of the above questions!
2