在Prolog中获取元组的第一个/第二个元素

时间:2018-05-14 10:44:30

标签: prolog tuples predicate

我还没有找到如何在Prolog中获取元组的第一个/第二个元素,我尝试了arg,但它只适用于谓词。 我的列表如下所示:

Pairs = [
  (pos(1, 2), pos(1, 3)),  
  (pos(1, 2), pos(2, 1)),  
  (pos(1, 2), pos(2, 3)),  
  (pos(1, 2), pos(3, 1)),  
  (pos(1, 2), pos(3, 2)),  
  (pos(1, 3), pos(2, 1)),  
  (pos(1, 3), pos(2, 3)),  
  (pos(..., ...), pos(..., ...)),  
  (..., ...)|...].

1 个答案:

答案 0 :(得分:3)

你不需要任何特殊谓词来做到这一点,只需unification,例如:

?- (A, B) = (pos(1, 2), pos(4, 3)).
A = pos(1, 2),
B = pos(4, 3).

?- (pos(X1, Y1), pos(X2, Y2)) = (pos(1, 2), pos(4, 3)).
X1 = 1,
Y1 = 2,
X2 = 4,
Y2 = 3.

统一可以发生在规则体内,也可以直接发生在规则的头部。考虑以下示例"访问"所有对:

visit_pairs([]).               % same as: %  visit_pairs([]).
visit_pairs([(A, B) | Xs]) :-  %   -->    %  visit_pairs([X|Xs]) :-
    writeln(first_pair(A)),    %          %      (A, B) = X,
    writeln(second_pair(B)),   %          %      writeln(first_pair(A)),
    visit_pairs(Xs).           %          %      writeln(second_pair(B)),
                               %          %      visit_pairs(Xs).

visit_pairs仅适用于元组列表,列表中的每个元素都必须与(A, B)统一。

?- visit_pairs([(pos(1, 2), pos(1, 3)),  (pos(1, 2), pos(2, 1)),  (pos(1, 2), pos(2, 3)),  (pos(1, 2), pos(3, 1)),  (pos(1, 2), pos(3, 2)),  (pos(1, 3), pos(2, 1)),  (pos(1, 3), pos(2, 3))]).
first_pair(pos(1,2))
second_pair(pos(1,3))
first_pair(pos(1,2))
second_pair(pos(2,1))
first_pair(pos(1,2))
second_pair(pos(2,3))
first_pair(pos(1,2))
second_pair(pos(3,1))
first_pair(pos(1,2))
second_pair(pos(3,2))
first_pair(pos(1,3))
second_pair(pos(2,1))
first_pair(pos(1,3))
second_pair(pos(2,3))
true.

另一种方法是使用nth0/3按索引访问一个特定元素,然后再使用unification解压缩元组:

?- Pairs = [(pos(1, 2), pos(1, 3)),  ...], nth0(0, Pairs, Elem), (A, B) = Elem.
Elem =  (pos(1, 2), pos(1, 3)),
A = pos(1, 2),
B = pos(1, 3).

但这看起来很不典型。