Prolog中不同变量的MIX值

时间:2012-07-03 21:37:00

标签: variables prolog mixing

我在Prolog中遇到一些简单程序的问题。我有两个不同的群体,我想将一个群体的元素附加到另一个群体,而不直接修改事实(例如:多伦多=美国)。

country(usa,    northamerica).
country(canada, northamerica).

city​​(chicago,    usa).
city​​(newyork,    usa).
city​​(losangeles, usa).
city​​(dallas,     usa).
city​​(miami,      usa).
city​​(lasvegas,   usa).
city​​(seattle,    usa).

city​​(toronto,    canada).
city​​(vancouver,  canada).
city​​(ottawa,     canada).
city​​(richmond,   canada).
city​​(winnipeg,   canada).
city​​(edmundston, canada).
city​​(hamilton,   canada).

trip(john, usa).
trip(jack, canada).

在这个例子中,约翰前往美国的七个城市,而杰克则前往加拿大其他七个城市。

然而,约翰最近前往多伦多。我想达到以下结果:

? - trip_plus(X, john).

X = chicago;
X = newyork;
X = losangeles;
X = dallas;
X = miami;
X = lasvegas;
X = seattle;
X = toronto;

?- yes

我多次试图获得上述结果失败。我能得到的最接近的是使用以下内容:

country(C).
city(Y).
trip(T).
trip_plus(X, T) :- city(Y, C), trip(T, C).

我做错了什么?

感谢队友。

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解你:你想创建一个谓词,列出有人访问过的所有城市吗?我会将我的解决方案分成三个案例。

首先,我们将列出所有直接“到城市旅行”,例如trip(john, toronto)trip(john, newyork)

trip_plus(City, Who) :-
  % we grab all the trip(*, *) pairs
  trip(Who, City),
  % and we leave only cities
  city(City, _).

然后我们要列出“乡村旅行”中的所有城市,例如trip(john, usa)

trip_plus(City, Who) :-
  % again, we grab all the trip(*, *) pairs
  trip(Who, Country),
  % and we list all cities in given country (if it is a country)
  city(City, Country).

最后,我们要列出“洲际旅行”中的所有城市,例如: trip(jack, northamerica)

trip_plus(City, Who) :-
  % the same thing
  trip(Who, Continent),
  % we list all countries on the continent
  country(Country, Continent),
  % and we list all cities in given country 
  city(City, Country).

整个谓词看起来像这样:

trip_plus(City, Who) :-
  trip(Who, City),
  city(City, _).
trip_plus(City, Who) :-
  trip(Who, Country),
  city(City, Country).
trip_plus(City, Who) :-
  trip(Who, Continent),
  country(Country, Continent),
  city(City, Country).

所以对于你的世界数据库和那些旅行:

trip(john, usa).
trip(jack, canada).
trip(john, toronto).

我们得到:

?- trip_plus(X, john).
X = toronto ;
X = chicago ;
X = newyork ;
X = losangeles ;
X = dallas ;
X = miami ;
X = lasvegas ;
X = seattle ;
false.

您可能会注意到toronto是第一个,而条目trip(john, toronto)在数据库中是最后一个。这是因为我们首先寻找“到城市”的旅行。如果订单对您很重要,谓词可能会写成:

trip_plus(City, Who) :-
  trip(Who, Where),
  (
  city(Where, _), City = Where;
  city(City, Where);
  country(Country, Where), city(City, Country)
  ).

但我个人觉得不太明显。

答案 1 :(得分:0)

嗯,你没有将“约翰前往多伦多”添加到事实清单中 它永远不会出现。您可以按如下方式修改代码:

%This is not needed => country(C). 

city(toronto). %here whatever city john visited
trip(john). %the person's name
trip_plus(X, T) :- trip(T,C), city(X,C) | trip(T) , city(X).