Week 6: Exercises

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

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

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

6. Or

Which of these functions is equivalent to the built-in operator || ?

  1. or _ True = True
    or True _ = True
    or _ _ = False

  2. or True False = True
    or True True = True
    or False True = True
    or False False = False

  3. or a b = b || a

7. Infinite Ints

Construct a list ints of integers from 1 to ∞. Do not use 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. Prime

Write a function that determines whether an integer is prime.

10. All Primes

Construct an infinite list containing all prime numbers.

11. Words

Write a function that breaks a string into a list of words.