1

我有一个谓词,目的是打印出哪个国家面积最大(边界最大的国家=最大面积)。这就是我的谓词的样子:

/* If I write get_country(X, 'Europe'). then all the countries in Europe 
that isn't bordering a sea gets printed out. 
However as you can see I am creating a list 
with all of the countries and then I want to
take the largest country from all of these 
and print that one out. But instead 
all of the countries gets printed out 
with their length, ex: X = hungary ; 359 (length) ...  */
get_country(Country, Region):-
    encompasses(Country,Region,_),
    not(geo_sea(_,Country,_)),
    setof(Length, country_circumference(Country,Length), Cs),
    largest(Cs, X),
    write(X).

该谓词中使用的谓词如下:

country_circumference(Country, X):-
    setof(Length, get_border_length(Country, Length), Cs),
    sum(Cs, X).

largest([X],X).
largest([X|Xs],R) :-
    largest(Xs,Y),
    R is max(X,Y).

谁能告诉我我在这里做错了什么?我如何简单地将我的所有国家/地区都放入列表中,然后遍历列表以找到具有最大边界的国家,而不是在我将它们放入列表时将它们一个接一个地打印出来?提前致谢。

4

1 回答 1

2

Prolog 定义了术语的自然顺序。例如,以下是正确的:

foo(3, z) @< foo(10, x)
bar(2, 9) @< foo(3, 1)

请注意术语比较运算符@<数字比较 <的使用。谓词 ,setof/3将进行术语比较。

如果您想找到具有最长边界的国家/地区,那么您可以通过利用术语比较来做到这一点,并收集setof/3具有您想要排序的项目作为第一个参数的类似术语。在这种情况下,我们首先需要圆周。此外,如果我get_country正确理解了谓词的预期含义,则需要将定义您要考虑的国家/地区的查询作为查询的一部分包含在setof/3

get_country(Country, Region):-
    setof(L-C-R, X^Y^Z^( encompasses(C, R, X),
                         \+ geo_sea(Y, C, Z),
                         country_circumference(C, L) ), Cs),
    reverse(Cs, HighToLowAreas),
    member(_-Country-Region, HighToLowAreas), !.

member/2谓词子句末尾的 将找到列表中HighToLowAreas与 匹配的第一个元素,如果和最初未实例化_-Country-Region,它将是第一个元素。CountryRegion

需要存在量词X^Y^Z^来将它们排除在查询中的选择器之外。using_不会在setof/3. 在这里,我们使用术语形式,-(-(X,Y),Z)因为它写得很方便,X-Y-Z. 但是你也可以在foo(X, Y, Z)这里使用。将reverse/2列表Cs降序排列,我们只需从该列表的头部选择Countryand , 。Region[_-Country-Region]

于 2015-03-03T12:17:07.820 回答