Week 10: Exercises

1. Infinite Iteration

The built-in function iterate produces an infinite list by repeated applying a function to a value:

iterate (*2) 1 => [1, 2, 4, 8, ...]

Write this function.

2. Infinite Diagonal Matrix

Construct an infinite diagonal matrix as an infinite list of lists:

[[1, 0, 0, 0, ...],
[0, 1, 0, 0, ...],
[0, 0, 1, 0, ...],
.
.
.
]

3. Pascal's Triangle

Recall that Pascal's triangle looks like this:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
. . .

Construct Pascal's triangle as an infinite list of lists:

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], ...]

4. Prime Sieve

Construct an infinite list of all prime numbers using the Sieve of Eratosthenes.

5. Fractions

Consider our generalized fraction type:

GFrac a = GFrac a a   -- numerator, denominator

Declare that the type is an instance of the Read and Show type classes.

6. Time

Create a Haskell type Time that represents a time of day with 1-second resolution, such as 5:15:02 or 13:12:45. Create a function of type Int -> Int -> Int -> Time that constructs a Time from values h, m, and s, where 0 <= h < 24 and 0 <= m, s < 60. Also declare that Time is an instance of the type classes Eq, Ord, Enum, Bounded, Read, and Show.

7. Balance Test

Define a balanced tree as follows: for any node, the number of nodes in the left and right subtrees differ by at most 1.

Write a function isBalanced that determines whether a tree is balanced. What is your function's worst-case big-O running time?