Week 3: Exercises

1. Natural Numbers

Write a predicate nat(N) that is true if N is any natural number, i.e. a non-negative integer. Your predicate should be able to generate all natural numbers.

2. Between

The built-in predicate between(+I, +J, ?K) is true if all arguments are integers and I ≤ K ≤ J. This predicate can generate all values between I and J. Write this predicate.

3. Reverse

Write a predicate reverse(L, M) that is true if L and M contain the same elements in reverse order.

4. Subset

Write a predicate subset(L, M) that is true if M is a subset of the elements in L, with elements in the same order as they appear in L.

5. Permutations

Write a predicate permutation(L, M) that is true if the list L is a permutation of M.

6. Combinations

Write a predicate combination(L, N, M) that is true if M is a combination of N elements of L, i.e. a subset of size N that has its elements in the same order as in L. Elements in M should appear in the same order as in L.

7. Addition

Suppose that we represent natural numbers using structures: 0 = z, 1 = s(z), 2 = s(s(z)) and so on.

Write a predicate sum(I, J, K) that is true if I + J = K, where I, J, and K have this numeric representation. Your predicate should work in all directions.

8. Multiplication

Suppose that we represent natural numbers using structures: 0 = z, 1 = s(z), 2 = s(s(z)) and so on.

Write a predicate mul(I, J, K) that is true if I · J = K, where I, J, and K have this numeric representation. Your predicate should work in all directions.

9. Lists from Structures

Without using Prolog's built-in list type, we may define lists using structures as follows. Let nil represent the empty list, and let cons(X, L) represent the value X prepended to the list L. With this list representation, write predicates member(X, L) and append(L, M, N).

10. Insertion Sort

Write a predicate insertion_sort(L, S) that sorts a list L of integers. Use an insertion sort.

11. Merge Sort

Write a predicate merge_sort(L, S) that sorts a list L of integers. Use a merge sort.

12. Quicksort

Write a predicate quicksort(L, S) that sorts a list L of integers. Use a quicksort. Use the first element of L as the pivot element.

13. Crosswords

Suppose that we'd like to fill in a 3 x 3 grid with letters so that every row and column contains one of these words:

AGE, AGO, CAN, CAR, NEW, RAN, ROW, WON

Write a Prolog program that can find all possible solutions.

14. Dictionary Update

We may represent a dictionary in Prolog using a list of pairs:

D = [ red : 10, green : 20, blue : 30, orange : 40 ].

Write a predicate update(+D, +K, +V, ?D1) that takes a dictionary D, a key K and a value V. It should return a dictionary D1 that is like D, but in which the key K has value V. If the key is not already present, it should be added.