Prolog 查找不相关的图节点
Prolog find non related graph nodes
我有下图:
我的目标是获取某个节点的所有直接连接以及与某个节点不连接的所有节点例如:
连接数(1,X).
X=3;
X=4;
X=5;
X=6.
noConnections(1,X).
X=2.
这是我的代码:
% knowledge base
path(1, 6).
path(1, 5).
path(1, 4).
path(1, 3).
path(6, 5).
path(5, 4).
path(4, 2).
path(2, 3).
% rules
connections(X,Y) :- path(X,Y) ; path(Y,X).
noConnections(X,Y) :- \+path(X,Y).
如您所见,我已成功完成 connections,但无法找到 noConnections
的操作方法
一种方式:
connected(X, Y) :-
path(X,Y);path(Y,X).
% fetching all nodes of the database
collectAllNodesButX(X, L) :-
setof(A, B^(path(A,B);path(B,A)), L1),
select(X, L1, L).
% main predicate
notConnected(X, L) :-
collectAllNodesButX(X,Nodes),
% we exclude all nodes that succeed the predicate connected/2
findall(Y, (member(Y, Nodes), \+connected(X, Y)), L).
现在,我们得到:
?- notConnected(1, L).
L = [2] .
?- notConnected(X, [2]).
X = 1 .
您可以使用 not(Goal)
谓词。你可以说 not(path(X,Y)); not(path(Y,X)).
这只是你目标的倒置。如果该节点直接连接到您正在检查的任何节点,则结果为 false。没有连接 returns true then.
我有下图:
我的目标是获取某个节点的所有直接连接以及与某个节点不连接的所有节点例如:
连接数(1,X).
X=3;
X=4;
X=5;
X=6.
noConnections(1,X).
X=2.
这是我的代码:
% knowledge base
path(1, 6).
path(1, 5).
path(1, 4).
path(1, 3).
path(6, 5).
path(5, 4).
path(4, 2).
path(2, 3).
% rules
connections(X,Y) :- path(X,Y) ; path(Y,X).
noConnections(X,Y) :- \+path(X,Y).
如您所见,我已成功完成 connections,但无法找到 noConnections
的操作方法一种方式:
connected(X, Y) :-
path(X,Y);path(Y,X).
% fetching all nodes of the database
collectAllNodesButX(X, L) :-
setof(A, B^(path(A,B);path(B,A)), L1),
select(X, L1, L).
% main predicate
notConnected(X, L) :-
collectAllNodesButX(X,Nodes),
% we exclude all nodes that succeed the predicate connected/2
findall(Y, (member(Y, Nodes), \+connected(X, Y)), L).
现在,我们得到:
?- notConnected(1, L).
L = [2] .
?- notConnected(X, [2]).
X = 1 .
您可以使用 not(Goal)
谓词。你可以说 not(path(X,Y)); not(path(Y,X)).
这只是你目标的倒置。如果该节点直接连接到您正在检查的任何节点,则结果为 false。没有连接 returns true then.