Week 6: Exercises

Solve the following problems in Haskell.

1. Length

Write the built-in length function that returns the length of a list.

2. Last Element

Write a function last that returns the last element of a list.

> last [2, 4, 6, 8]
8

3. Second Last

Write a function secondLast that returns the second-to-last element of a list.

> secondLast [2, 4, 6, 8]
6

4. k-th element

Write a function kth that returns the kth element of a list, where elements are numbered starting from 0. (Do not use the built-in operator !!, which does the same thing.)

5. Zip

Implement the built-in function zip that converts two lists into a list of pairs:

> zip [10, 12, 14] [21, 23, 25, 27]
[(10,21),(12,23),(14,25)]

Stop zipping when you reach the end of either list.

6. Deduplicate

Write a function dedup that eliminates consecutive duplicate elements in a list:

> dedup [2, 4, 4, 4, 6, 6, 8, 4]
[2, 4, 6, 8, 4]

7. Combine

Write a function combine that groups consecutive duplicates into sublists:

> combine [2, 4, 4, 4, 6, 6, 8, 4]
[[2], [4, 4, 4], [6, 6], [8], [4]]