你需要即是實例定義一個謂詞is_leaf/1
這是一個發電機, 輸入變量有可能的解決方案。
事情是這樣的:
% Directed graph
de(0,1).
de(0,2).
de(2,3).
de(2,4).
de(3,4).
de(4,5).
% If Node is ground,
% then test if it is a child node that is not a parent node.
% If Node is not ground,
% then bind it to a child node that is not a parent node.
is_leaf(Node) :-
de(_, Node),
\+ de(Node, _).
使用示例:
?- is_leaf(Node).
Node = 1 ;
Node = 5.
?- is_leaf(Node), writeln(Node), fail ; true.
1
5
true.
?- findall(Node, is_leaf(Node), Leaf_Nodes).
Leaf_Nodes = [1, 5].
您的解決方案會立即調用not
。 (順便說一句,SWI-Prolog的建議使用\+
代替not
。)
isLeaf(Node) :-
not(de(Node,_)).
這意味着你的isLeaf/2
不是發電機:它要麼失敗或成功(一次),從來沒有結合的輸入參數,如果它恰好是一個變量。 此外,它從不測試輸入是葉,它只是測試它是否不是父節點。
% Is it false that 1 is a parent? YES
?- isLeaf(1).
true.
% Is it false that blah is a parent? YES
?- isLeaf(blah).
true.
% Is it false that 2 is a parent? NO
?- isLeaf(2).
false.
% Basically just tests if the predicate de/2 is in the knowledge base,
% in this sense quite useless.
?- isLeaf(Node).
false.