如何在Prolog中返回嵌套列表的所有元素?现有代码仅返回首个子列表元素
Your current code only returns elements from the first sublist because once that sublist is exhausted (becomes empty), there's no logic to move on to the remaining sublists in the outer list. Plus, there's a small typo in the second clause (return_list_members instead of treturn_list_members).
Here's how to fix it by adding a clause to handle empty sublists and proceed to the next ones:
% Return the head of the first non-empty sublist treturn_list_members([[Head|_]|RestOuter], Head). % Process the tail of the current sublist to get remaining elements treturn_list_members([[_|Tail]|RestOuter], Member) :- treturn_list_members([Tail|RestOuter], Member). % When the current sublist is empty, move to the next sublist in the outer list treturn_list_members([[]|RestOuter], Member) :- treturn_list_members(RestOuter, Member).
Testing this with your query:
?- treturn_list_members([[12,3],[45,6],[11,90]],L).
Will now return all elements:
L = 12 ; L = 3 ; L = 45 ; L = 6 ; L = 11 ; L = 90 ; false.
A More Concise Approach
If you don't mind using Prolog's built-in predicates, you can simplify this drastically by combining member/2 to iterate over both the outer list and each inner list:
treturn_list_members(OuterList, Member) :- member(Sublist, OuterList), member(Member, Sublist).
This works because member(Sublist, OuterList) picks each sublist in sequence, and member(Member, Sublist) retrieves every element from that sublist before moving to the next one. It produces the exact same result as the custom implementation above.
内容的提问来源于stack exchange,提问作者Arnau Van Boschken ArnauB

