在Prolog规则中使用事实清单 [英] Using a list from a fact within Prolog rules

查看:85
本文介绍了在Prolog规则中使用事实清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写铁路计划,但使用事实清单会遇到一些麻烦.我对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).,它将返回false.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆