prolog中列表中的列表

时间:2011-03-09 01:49:11

标签: list prolog

我在prolog中有以下列表:

[[1,2],[2,3]]

现在,我可以像这样在列表中进行简单的遍历:

traverse([]).

traverse([H|T]):-
   write(H),
   traverse(T).

但是,我不想要这个;我希望能够以列表本身的形式访问列表中的每个元素,而不是简单的变量。我想要做的就是将H的每次迭代转换成一个列表,这样我就可以打印出H中的第一个或第二个值。但是,我无法在prolog中提出语法来做所以。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您需要使用列表构造函数统一(而不是强制转换)H变量。

traverse([H|T]) :-
  (
     H = [],
     % The list within the list is the empty list.
  ;
     H = [HH | HT]
     % HH is the head of the list within the list.
     % HT is the tail of the list within the list (note, not the second item in the list).
  ),
  traverse(T).

这个析取(操作符的两个操作数)与遍历的两个子句的头部中发生的相同。 因此,也可以使用单独的谓词来遍历列表中的列表。

答案 1 :(得分:0)

我不清楚你在追求什么,但是有以下任何一种帮助吗?

% process head and tail recursively, feeding all leaves to write()
write_leaves([]).
write_leaves([H|T]) :- write_leaves(H), write_leaves(T).
write_leaves(X) :- write(X).

或者

% process_list iterates over just one level of list;
% process_item decides what to do with each element.
process_item([1|T]) :- write(T).
process_item([H|_]) :- write(H).
process_list([]).
process_list([H|T]) :- process_item(H), process_list(T).

如果这些都不是你想要的,那么你的问题可能更明确一些。

相关问题