2

我正在使用如下所示的谓词:

predicate(Country, X):-
    setof(Length, anotherPredicate(Country,Length), X).

我的问题是我的代码为每个值返回列表 X。我想要的是返回一个包含所有数字的大列表,因为现在我得到了答案:

Country = adsfsadf;
X = [123];
Country = asfdsaf;
X = [312];

因此,每次我想要一个包含所有内容的大列表时,而不是小列表。

编辑评论 ----------

predicate(Country, Length) :-
   setof(p(ML,C,L),
      ( anotherPredicate(C, L), ML is -L ),
      [p(_,Country, Length)|_]).

这是我写的,它立即给了我错误。

4

2 回答 2

3

目前,您会为Country. 之所以如此,是因为setof/3识别所有自由变量并为这些变量的每个不同实例生成一个列表。

但是你问的是不一致的。一方面,您希望只有一个列表。这很容易提供,前提是您可以轻松构建解决方案集。

 setof(Length, Country^anotherPredicate(Country,Length), X).

另一方面,您仍然希望该Country变量作为predicate/2! 的第一个参数出现。这没有任何意义。只不过是坚持局部变量存在于外部上下文中。不幸的是,Prolog 不能直接检测到此类错误。对于与

predicate(Country, X):-
    setof(Length, Country^anotherPredicate(Country,Length), X).

?- predicate(C, L).
L = [length_of_1, length_of_2].

?- C = c1, predicate(C, L).
C = c1,
L = [length_of_1].

也就是说,通过专门化目标(通过添加C = c1),L可以找到不同的目标。

然而,有一个警告:如果有两个长度相同的国家,比如 23,结果应该是什么?你想要一个[23]或两个元素[23,23]吗?从你的描述中看不清楚。

如果你想要两个,你必须首先确定:

setof(Country-Length, anotherPredicate(Country, Length), CL),
keys_values(CL, Lengths),
...

编辑:回应您的评论:

biggestcountry_val(Country, Length) :-
   setof(p(ML,C,L),
      ( anotherPredicate(C, L), ML is -L ),
      [p(_,Country, Length)|_]).
于 2014-10-22T09:17:29.243 回答
1

如果没有一些样本数据和预期/期望的结果,很难说出您需要什么。但是...检查谓词中参数的状态可能会为您提供所需的内容。

例如,给定以下数据:

foo( albania ,  1 ) .
foo( albania ,  2 ) .
foo( albania ,  3 ) .
foo( albania ,  4 ) .
foo( albania ,  5 ) .
foo( albania ,  6 ) .
foo( iceland ,  4 ) .
foo( iceland ,  5 ) .
foo( iceland ,  6 ) .
foo( iceland ,  7 ) .
foo( iceland ,  8 ) .
foo( iceland ,  9 ) .
foo( france  ,  7 ) .
foo( france  ,  8 ) .
foo( france  ,  9 ) .
foo( france  , 10 ) .
foo( france  , 11 ) .
foo( france  , 12 ) .

您对问题中显示的内容的初步看法

predicate(Country, X):-
  setof(Length, foo(Country,Length), X).

Country以未绑定变量调用时返回以下多个结果:

?- predicate(Country,X).
Country = albania , X = [1, 2, 3, 4, 5, 6] ;
Country = france  , X = [7, 8, 9, 10, 11, 12] ;
Country = iceland , X = [4, 5, 6, 7, 8, 9] .

Country如果在绑定到有效国家/地区的情况下调用这个单一结果,iceland在这种情况下:

?- predicate(iceland,X).
X = [4, 5, 6, 7, 8, 9].

然而,如果你做这样的事情,

predicate( C , Xs ) :- var(C)    , setof( X , C^foo(C,X) , Xs ) .
predicate( C , Xs ) :- nonvar(C) , setof( X ,   foo(C,X) , Xs ) .

当参数未绑定时,您将获得这个解决方案:

?- try_this(C,Xs).
Xs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ;
false.

你会注意到它C仍然不受约束。

当参数被绑定时,你会得到这个结果:

?- try_this(iceland,Xs).
Xs = [4, 5, 6, 7, 8, 9].
于 2014-10-22T17:30:12.180 回答