Week 4: Exercises

1. All Same

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

2. Writing maplist()

The predicate maplist(P, L, M) takes a predicate P of two arguments. Implement this version of maplist() using call().

3. Matrices

We can represent a matrix as a list of lists of floating-point numbers.

Write a predicate size(M, N) that is true if M is a square matrix with dimensions N x N.

Also write predicates that can calculate the following:

  1. the zero matrix of a given size

  2. the sum of two matrices

  3. the product of a scalar and a matrix

  4. the first column of a matrix (a vector)

  5. the identity matrix of a given size

  6. the transpose of a matrix

All predicates should work in any direction.

4. 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 predicate that can find all possible solutions.

5. Cryptarithmetic

In this cryptarithmetic puzzle, every letter stands for a different digit:

  A P P L E
+ G R A P E
+   P L U M
=========== 
B A N A N A

Write a Prolog program that can find a solution to the puzzle.

6. N Queens

Consider the famous N queens problem: can we place N queens on an N x N chessboard such that no queen attacks any other? Write a Prolog predicate that can solve this problem for any given N.