Week 9: Exercises

1. Function Types

What are the types of these functions?

  1. triple x = 3 * x

  2. even x = (x `mod` 2 == 0)

  3. palindrome xs = (reverse xs == xs)

  4. f x = f x

2. List Functions

Write these functions (which are all built into the standard library):

a) isPrefixOf :: Eq a => [a] → [a] → Bool

Take two lists and return true if the first list is a prefix of the second.

b) isInfixOf :: Eq a => [a] → [a] → Bool

Take two lists and return true if the first list is contained anywhere within the second.

c) group :: Eq a => [a] → [[a]]

Group adjacent identical elements into sublists. For example,


group "Mississippi" == ["M","i","ss","i","ss","i","pp","i"]

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

4. Fibonacci Numbers

Construct an infinite list containing all Fibonacci numbers: 1, 1, 2, 3, 5, 8, 13, ...

5. Prime

Write a function that determines whether an integer is prime.

6. All Primes

Construct an infinite list containing all prime numbers.

7. Greatest Common Divisor

Write a function that computes the greatest common divisor of two numbers. It should work with any integral type, e.g. either Int or Integer.

8. Vector Sum

Write a function add_vec that adds two vectors represented as lists. Give your function the most general possible type.

9. Dot Product

Write a function dot that computes the dot product of two vectors represented as lists.

10. Matrix Addition

Write a function add that adds two matrices represented as lists of lists.