Sorry if this is a dumb question, but I’m confused.
Whilst trying to work out why my code required me to press ;
before I ended, even though there was only one solution, I came across the concept of choice points. Whilst I think I understand the idea, I can’t get my head around how it actually works.
For example, someone asked about this on SO, and whilst the answer there shows another way of writing the predicate to avoid choice points, it didn’t explain why there was a choice point in the first place.
The original code (which removed the last element from the list in the first argument) was…
list_withoutlast([_Last], []).
list_withoutlast([First, Second|List], [First|WithoutLast]) :-
list_withoutlast([Second|List], WithoutLast).
If you try list_withoutlast([1], Res).
then you get the result (Res = []
), but then hit a choice point. Pressing *
for more info gives…
% list_withoutlast([1],[]) left a choice point in alternate clause (after success)
% c:/users/me/documents/prolog/choicepoints.pl:1: clause succeeded
% c:/users/me/documents/prolog/choicepoints.pl:2: next candidate clause
% Called from
% [9] toplevel_call(user:user: ...) at c:/program files/swipl/boot/toplevel.pl:1173
I really don’t understand this. That second predicate has a head whose first argument accepts a list with at least two elements, plus a (possibly empty) tail. How can Prolog think that this is a potential match when the list it’s handling only has one element?
Thanks for any help you can give.