1
votes

I have an exam in Prolog today and am revising for it using old questions.

Would answer c be the incorrect answer? Can anyone please explain this to me? It would be very helpful. Thank you,

Consider the following predicate:

swap([], []).
swap([X1, X2 | L], [X2, X1 | S]) :- swap(L, S).

Which of the following query and answer pairs is incorrect:

(a) ?- swap([a,b,c,d], S).
S = [b, a, d, c].

(b) ?- swap([a,b,d], H).
false.

(c) ?- swap([a,a,b,b], S).
S = [b, b, a, a].

(d) ?- swap([], S).
S = [].
1
C would be incorrect. Look carefully at the predicate and pretend you're the prolog interpreter. Then match your input with the roght clause and see what happens. - lurker

1 Answers

0
votes

(c) is indeed the incorrect answer. Item (c) has the following query:

swap([a,a,b,b], S).

If you run this query manually, it clearly doesn't match the clause swap([], []). It then does match the second clause: swap([X1,X2|L], [X2,X1|S]) :-....

swap([a,  a,   b, b], S).
swap([X1, X2 | L],   [X2, X1 | S]) :- swap(L, S).
==> X1 = a, X2 = a, L = [b, b]
==> swap([a, a| [b,b]], [a, a | S]) :- swap([b, b], S).

Prolog can instantiate the first argument [X1,X2|L] with the given list, [a,a,b,b]. That, then, means X1 = a, X2 = a, and the rest of the list, L = [b,b]. Already from this information, you know that the list [X2,X1|S] is [a,a|S] but the answer shown by (c) is [b,b,a,a]. You don't even need to find out what S because since you know alrady that [a,a|S] isn't going to match [b,b,a,a].