我正在为大学考试学习 Prolog,但我在这个练习中遇到了问题:
not_member(X,L)
如果元素X
不属于列表,则实现为 TRUE 的谓词L
。
如果我的推理是正确的,我已经找到了解决方案:
% 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
为什么?