Prolog, predicate returns 结果正确,还假?
Prolog, predicate returns the correct result, but also false?
我发现对于我的大部分谓词,prolog 找到了多个解决方案,其中一个是正确的结果,另一个是 'false.'
演示:
%finds the last element of list, or false if empty.
last([H|L], More):-
last(L, More).
last([H], H).
运行 这给出:
?- last([a, b, c], W).
W = c ;
false.
谁能解释一下为什么它还提供 'false.'?这是我需要解决的问题吗?
你没有做错任何事,这也不是要解决的问题。序言通过在末尾打印 false
告诉您的是,除了它已经向您展示的解决方案之外,没有其他解决方案。 (请注意,点击 ;
会告诉 prolog 显示更多答案,您也可以点击 return 来简单地终止查询。)
有关详细信息,请参阅 https://www.swi-prolog.org/download/stable/doc/SWI-Prolog-8.2.1.pdf 的第 2.1.3 节。
你可以稍微修改一下:
last(List, Last):- last(List, _, Last).
last([H | T], _, Last):-
last(T, H, Last).
last([], Last, Last). % Unify H and Last - no other solution
简单的解决方案:
last(List, Last) :-
once(append(_, [Last], List)).
我发现对于我的大部分谓词,prolog 找到了多个解决方案,其中一个是正确的结果,另一个是 'false.'
演示:
%finds the last element of list, or false if empty.
last([H|L], More):-
last(L, More).
last([H], H).
运行 这给出:
?- last([a, b, c], W).
W = c ;
false.
谁能解释一下为什么它还提供 'false.'?这是我需要解决的问题吗?
你没有做错任何事,这也不是要解决的问题。序言通过在末尾打印 false
告诉您的是,除了它已经向您展示的解决方案之外,没有其他解决方案。 (请注意,点击 ;
会告诉 prolog 显示更多答案,您也可以点击 return 来简单地终止查询。)
有关详细信息,请参阅 https://www.swi-prolog.org/download/stable/doc/SWI-Prolog-8.2.1.pdf 的第 2.1.3 节。
你可以稍微修改一下:
last(List, Last):- last(List, _, Last).
last([H | T], _, Last):-
last(T, H, Last).
last([], Last, Last). % Unify H and Last - no other solution
简单的解决方案:
last(List, Last) :-
once(append(_, [Last], List)).