Prolog 陷入无限循环

问题描述 投票:0回答:1

我需要将每个元素写一次,例如,比利时与法国接壤,它应该自动暗示法国与比利时接壤。 不幸的是,语句

borders(X, Y) :- borders(Y, X).
陷入了无限循环。

% Knowledge
borders('Belgium', 'France').
borders('Belgium', 'Germany').
borders('Belgium', 'Luxembourg').
borders('Belgium', 'Netherlands').
borders('Denmark', 'Germany').
borders('France', 'Germany').
borders('France', 'Luxembourg').
borders('Germany', 'Luxembourg').
borders('Germany', 'Netherlands').

% Rule
borders(X, Y) :- borders(Y, X).

它向我展示了以下所有内容

? - borders('France', X).
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium' ;
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium' ;
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium' ;
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium' ;
X = 'Germany' . 

虽然它应该停在边界

? - ('France', X).
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium'
loops prolog
1个回答
0
投票

为了避免无限循环,请使用不同的谓词名称(例如,

borders
border
):

borders(X, Y) :- border(X, Y).
borders(X, Y) :- border(Y, X).

border('Belgium', 'France').
border('Belgium', 'Germany').
border('Belgium', 'Luxembourg').
border('Belgium', 'Netherlands').
border('Denmark', 'Germany').
border('France', 'Germany').
border('France', 'Luxembourg').
border('Germany', 'Luxembourg').
border('Germany', 'Netherlands').

示例:

?- borders('France', X).
X = 'Germany' ;
X = 'Luxembourg' ;
X = 'Belgium'.
© www.soinside.com 2019 - 2024. All rights reserved.