Homework 8 Answers
Part I
Question 1
a. X < 7 (Y is not really an unknown)
b. L = 3
c. CLPR does not offer to retry for the query in b
d. Xs = any list, L is the length of Xs + 2
e. Xs = any list with 3 elements
f. CLPR says "No" when you tell it to retry the query in e
g. Xs = the empty list or any list whose elements are 1
h. Xs = [1, 1, 1]
Question 2
sum([], 0).
sum([X | Xs], S + X) :- sum(Xs, S).
Part II
Question 1
same_length([], []).
same_length([_ | Xs], [_ | Ys]) :- same_length(Xs, Ys).
OR:
same_length(Xs, Ys) :- length(Xs, L), length(Ys, L).
The second version gives the "retry" behavior as shown in the question.
Question 2
index([X | _], 0, X).
index([_ | L], I, X) :- I > 0, index(L, I - 1, X).
Question 3
Assume that a matrix with no columns or no rows is not a real matrix.
matrix(M) :- matrix_helper(M, _).
matrix_helper([], _).
matrix_helper([X | Xs], C) :- length(X, C), matrix_helper(Xs, C).
OR:
matrix([[_ | _]]).
matrix([X, Y | Xs]) :- length(X, C), length(Y, C), matrix([Y | Xs]).
The second version gives the "retry" behavior as shown in the question.