Week 7: Exercises

Solve the following problems in Haskell.

1. Last Element

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

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

2. Second Last

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

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

3. 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.

4. Unzip

Implement the built-in function unzip that converts a list of pairs into a pair of lists:

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

5. Flatten

Write a function flatten that flattens a list of lists into a single list:

> flatten [[2, 4], [6, 8], [10]]
[2, 4, 6, 8, 10]

6. Reverse a List

Implement the built-in function reverse that reverses a list:

> reverse [2, 4, 6]
[6,4,2]

Your function should run in linear time.

7. Infinite Ints

Construct a list ints of integers from 1 to ∞, without using the built-in range operator (i.e. [1 .. ]).

8. Cyclic List

Implelement the built-in function cycle that takes a list L and returns an infinite list consisting of L repeated over and over:

> take 10 (cycle "abc")
"abcabcabca"

9. Termination

Consider these definitions:

infinite x = infinite x

second a b = if b > 0 then b else a

rep x = x : rep x

Which of these queries will terminate?

  1. infinite 0

  2. second (infinite 0) 5

  3. length (take 3 (rep (infinite 0)))

10. Primality Test

Write a function isPrime that determines whether an integer is prime.

11. 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]

12. 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]]