在查询中询问时如何编写规则以列出所有城市?

时间:2019-04-24 04:38:13

标签: prolog

如何设置规则以及何时要求查询列出所有可行的城市?

/*CITY DATABASE */
capital(bern).
capital(london).
capital(prague).
capital(bonn).
capital(belgrade).

city_in(prague,czechoslovakia).
city_in(berlin,germany).
city_in(hamburg,germany).
city_in(belgrade,yugoslavia).
city_in(bern,switzerland).
city_in(london,united_kingdom).

belongs_to(czechoslovakia,’COMECON’).
belongs_to(germany,’EC’).
belongs_to(switzerland,’EFTA’).
belongs_to(united_kingdom,’EC’).

/*END*/

1 个答案:

答案 0 :(得分:1)

要获取此规则集可用的城市的完整列表,以下查询将在X变量(在SWI-Prolog中测试)中列出您的所有城市:

city_in(X, _).

要将城市转换为一个列表,请使用findall/3Xs将得到结果):

findall(X, city_in(X, _), Xs).

如果您要获取某个组织的城市列表,则可以发出以下内容,并获取该组织中存在的国家和城市列表:

belongs_to(Country, _), city_in(X, Country).

同样,针对findall/3的回复列表:

findall(X, (belongs_to(Country, _), city_in(X, Country)), Xs).

属于某个组织的首府城市列表(在“城市”变量中列出):

belongs_to(Country, _), city_in(City, Country), capital(City).

并且,对于属于findall/3的组织的城市列表:

findall(City, (belongs_to(Country, _), city_in(City, Country), capital(City)), Cities).

以上内容的输出

?- findall(City, (belongs_to(Country, _), city_in(City, Country), capital(City)), Cities).
Cities = [prague, bern, london].