I have the following list in prolog:
[[1,2],[2,3]]
Now, I can do a simple traversal in the list like this:
traverse([]).
t开发者_运维问答raverse([H|T]):-
write(H),
traverse(T).
But, I don't want this; I want to be able to access each element in the list as a list itself, not as a simple variable. What I want to do, out of this, is to cast each iteration of H into a list, so I can print out either the first or second value in H. However, I can't come up with the syntax in prolog to do so. Can anyone help?
You need to unify (not cast) the H variable with the list constructor.
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).
This disjunction (the two operands to the ; operator), is the same as what's happening in the heads of the two clauses of traverse. Therefore a separate predicate could also be used to traverse the list inside the list.
It's not perfectly clear to me what you're after, but does either of the following help?
% 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).
or maybe
% 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).
If neither of these is close to what you want, it might be worth making your question a bit more explicit.
精彩评论