在 Prolog 规则中使用事实列表 [英] Using a list from a fact within Prolog rules
问题描述
我目前正在编写一个铁路线程序,但在使用来自事实的列表时遇到了一点麻烦.我对 Prolog 很陌生,到目前为止,我已经写了以下事实和规则:
I am currently writing a rail line program but am having a little trouble using lists that come from facts. I am quite new to Prolog and so far have written the following facts and rules:
location(euston, [northernLine]).
location(warrenStreet, [victoriaLine, northernLine]).
location(warwickAvenue, [bakerlooLine]).
location(paddington, [bakerlooLine]).
hasCommonLine(Location1, Location2, Line) :-
location(Location1, Line),
location(Location2, Line).
这个想法是让规则返回两个位置共有的行的名称.如果我尝试 hasCommonLine(warwickAvenue,paddington,Line).
这会有效,但是如果我尝试 hasCommonLine(euston,warrenStreet,Line).
.
The idea is for the rule to return the name of the line(s) that the two locations have in common. This works if I try hasCommonLine(warwickAvenue,paddington,Line).
, however it returns false if I try hasCommonLine(euston,warrenStreet,Line).
.
我怀疑这是因为规则只检查列表的第一个元素,因此只比较 [northernLine]
和 [victoriaLine]
而不是检查列表中的每个元素列表.任何指导来实现这一点将不胜感激!
I suspect this is because the rule only checks the first element of the lists, therefore only compares [northernLine]
and [victoriaLine]
rather than checking every element in the list. Any guidance to accomplish this would be much appreciated!
推荐答案
您可以检查 Line
是否是两个列表的成员:
You can check if Line
is a member of both lists:
hasCommonLine(Location1, Location2, Line) :-
location(Location1, Lines1),
location(Location2, Lines2),
member(Line, Lines1),
member(Line, Lines2).
然后,如果您需要找到两个位置之间的所有公共线,您只需调用
Then, if you need to find all the lines common between two locations, you would simply call
?- findall(X, hasCommonLine(euston, warrenStreet, X), Y).
Y = [northernLine].
这篇关于在 Prolog 规则中使用事实列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!