Reputation: 345
I found that for most of my predicates, prolog finds multiple solutions, with one of them being the correct result, the other is 'false.'
To demontrate:
%finds the last element of list, or false if empty.
last([H|L], More):-
last(L, More).
last([H], H).
running this gives:
?- last([a, b, c], W).
W = c ;
false.
Can anyone explain why it is giving 'false.' in addition? Is this something I need to fix?
Upvotes: 3
Views: 611
Reputation: 31
You can modify it a bit:
last(List, Last):- last(List, _, Last).
last([H | T], _, Last):-
last(T, H, Last).
last([], Last, Last). % Unify H and Last - no other solution
Simple solution:
last(List, Last) :-
once(append(_, [Last], List)).
Upvotes: 2
Reputation: 30418
You're not doing anything wrong, nor this is something to fix. What prolog is telling you by printing false
at the end is that there are no other solutions than the ones it has already shown you. (Note that hitting ;
tells prolog to show you more answers, you can also hit return to simply terminate the query.)
See Section 2.1.3 of https://www.swi-prolog.org/download/stable/doc/SWI-Prolog-8.2.1.pdf for details.
Upvotes: 2