簡體   English   中英

Prolog,predicate返回正確的結果,還為假?

[英]Prolog, predicate returns the correct result, but also false?

我發現對於我的大多數謂詞,prolog 找到了多個解決方案,其中一個是正確的結果,另一個是“錯誤的”。

證明:

%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.

誰能解釋為什么它給出“假”。 此外? 這是我需要解決的問題嗎?

你沒有做錯任何事,這也不是要解決的問題。 prolog 通過在最后打印false告訴您的是,除了它已經向您展示的解決方案之外,沒有其他解決方案。 (請注意,點擊;會告訴 prolog 向您顯示更多答案,您也可以點擊返回來簡單地終止查詢。)

有關詳細信息,請參閱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)).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM