Week 2: Exercises

1. s(s(s(X)))

(Bratko, ex. 2.6)

Consider this program:

f(1, one).
f(s(1), two).
f(s(s(1)), three).
f(s(s(s(X))), N) :- f(X, N).

What answer(s) will these queries produce?

  1. f(s(1), A).
  2. f(s(s(1))), two).
  3. f(s(s(s(s(s(s(1))))))), C).
  4. f(D, three).

2. Second Last

Write a predicate second_last(X, L) that is true if X is the next-to-last element of L.

3. Next To

Write a predicate next_to(X, Y, L) that is true if elements X and Y appear in L, with Y immediately after X.

4. Even Length

Write a predicate even_length(L) that is true if the length of L is an even integer.

5. Same Length

Write a predicate same_length(L, M) that is true if L and M have the same length.

6. Longer

Write a predicate longer(L, M) that is true if L is longer than M. Do not use any numbers in your solution.

7. Double Length

Write a predicate double_length(L, M) that is true if L is twice as long as M. Do not use any numbers in your solution.

8. Reverse

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

9. Rotate

When we rotate a list one element to the right, the last element moves to the first position and all other elements shift rightward.

Write a predicate rotate(L, M) that is true if M is L rotated one element to the right (or, equivalently, L is M rotated one element to the left).

10. Select

Write a predicate select(X, L, M) that is true if X can be removed from L to make M. Equivalently, select(X, L, M) is true if X can be inserted anywhere in M to make L.

11. Select, Extended

Write a predicate select(X, L, Y, M) that is true if L and M are identical except (possibly) for a single element, which is X in L and is Y in M.

12. All Same

Write a predicate all_same(L) that is true if all elements of L are identical.

13. All Different

Write a predicate all_diff(L) that is true if no two elements of L are identical.

14. Zip

Write a predicate zip(L, M) that is true if L is a list of pairs and M is a corresponding pair of lists, where we represent pairs using the structure pair(X, Y). For example, the following is true:

15. Numerals

Write a predicate numerals(L, M) that is true if L is a list of integers in the range 1 ≤ i ≤ 5 and M is a corresponding list of atoms from the set [ one, two, three, four, five ]. For example, numerals([2, 3, 2], [two, three, two]) is true.

16. Flatten

Write a predicate flatten(L, M) that is true if L is a list of lists and M is the concatenation of all those lists. For eample, flatten([[a, b], [c], [d, e]], [a, b, c, d, e]) is true.