我學習Prolog的一個大學考試,我有這個練習的問題:實現一個Prolog謂詞,指出一個元素是否屬於一個列表。有沒有數值列表問題
Implement the predicate
not_member(X,L)
that is TRUE if the elementX
does not belong to the listL
.
如果我的推論是正確的,我已經找到了解決辦法:
% FACT (BASE CASE): It is TRUE that X is not in the list if the list is empty.
not_member(_,[]).
% RULE (GENERAL CASE): If the list is non-empty, I can divide it in its Head
% element and the sublist Tail. X does not belong to the list if it is different
% from the current Head element and if it does not belong to the sublist Tail.
not_member(X,[Head|Tail]) :-
X =\= Head,
not_member(X,Tail).
這代碼與數字列表一起工作良好,如以下查詢所示:
2 ?- not_member(4, [1,2,3]).
true.
3 ?- not_member(1, [1,2,3]).
false.
但是,列表中包含一些非數字元素, 它不起作用並報告錯誤:
4 ?- not_member(a, [a,b,c]).
ERROR: =\=/2: Arithmetic: `a/0' is not a function
爲什麼?
好的,tnx這麼多。只有一點澄清:你爲什麼使用:not_member(_,[]): - !相反:not_member(_,[])。 究竟是什麼意思! ? Tnx – AndreaNobili 2013-04-07 17:24:38
(不是一個詳細的解釋)這是一個切割。它可以防止回溯,但這不是強制性的。在這種情況下可以使用它,因爲一旦統一在not_member(_,[])上成功了。我們不需要檢查其他的「解決方案」,所以我們「切斷」序言搜索樹並停止計算。 – Haile 2013-04-07 17:32:22