Managing nested lists in SWI-Prolog relies heavily on recursion and pattern matching, just like managing flat lists. The key difference is that you'll often need to check if an element is itself a list and then recurse into it if it is.
Let's break down how to work with them.
What is a Nested List?
A nested list is simply a list where some or all of its elements are themselves lists.
Examples:
[a, b, [c, d], e]
[[1, 2], [3, 4], [5, 6]]
[item1, [subitem1, [subsubitem1, subsubitem2]], item2] (deeply nested)
[] (empty list) is a list. [[]] is a nested list containing an empty list.
Key Tools for Nested List Management
- Pattern Matching (
[Head|Tail]): Still the fundamental way to decompose a list.
- Recursion: Essential for processing elements at any level of nesting.
is_list(Term): A crucial built-in predicate that succeeds if Term is a list, and fails otherwise. This allows you to differentiate between an atom/number and a nested list.
Common Operations on Nested Lists
Let's look at some common tasks:
1. Checking for Membership (nested member/2)
How to determine if an element exists anywhere within a nested list structure.
% nested_member(Element, NestedList)
% Base case 1: Element is the head of the current list
nested_member(X, [X|_]).
% Recursive case 1: Element is in the tail of the current list
nested_member(X, [_|T]) :-
nested_member(X, T).
% Recursive case 2: The head of the current list is itself a list,
% so check for membership within that sublist.
nested_member(X, [H|_]) :-
is_list(H), % Check if H is a list
nested_member(X, H). % Recurse into the sublist H
Explanation:
- The first clause (
nested_member(X, [X|_])) handles the direct match: if X is the first element of the list.
- The second clause (
nested_member(X, [_|T])) handles the recursive search: if X isn't the first element, try finding it in the rest of the list (T).
- The third clause (
nested_member(X, [H|_]) :- is_list(H), nested_member(X, H).) is the crucial part for nested lists. If the Head of the current list (H) is itself a list (is_list(H)), then we recursively call nested_member on that sublist H.
Queries:
?- nested_member(c, [a, b, [c, d], e]).
true.
?- nested_member(x, [a, b, [c, d], e]).
false.
?- nested_member(3, [[1, 2], [3, 4], [5, 6]]).
true.
?- nested_member(subsubitem1, [item1, [subitem1, [subsubitem1, subsubitem2]], item2]).
true.
?- nested_member([], [[], [a,b]]). % Check for an empty list as an element
true.
?- nested_member(a, [[], [a,b]]).
true.
2. Flattening a Nested List
Converting a nested list into a single, non-nested (flat) list.
% flatten_list(NestedList, FlatList)
% Base case: An empty list flattens to an empty list.
flatten_list([], []).
% Recursive case 1: If the Head is a list, flatten it and append to the flattened Tail.
flatten_list([H|T], FlatList) :-
is_list(H),
flatten_list(H, FlatH), % Flatten the head (which is a list)
flatten_list(T, FlatT), % Flatten the tail
append(FlatH, FlatT, FlatList). % Append the results
% Recursive case 2: If the Head is not a list, it's an element, so prepend it.
flatten_list([H|T], [H|FlatT]) :-
\+ is_list(H), % H is not a list
flatten_list(T, FlatT). % Flatten the tail
Explanation:
flatten_list([], []).: The base case. An empty list becomes an empty list.
flatten_list([H|T], FlatList) :- is_list(H), ...: If the Head (H) is a list, we recursively flatten H into FlatH and T into FlatT. Then, we concatenate FlatH and FlatT to get the final FlatList. This is where append/3 (a built-in for concatenating lists) comes in handy.
flatten_list([H|T], [H|FlatT]) :- \+ is_list(H), ...: If the Head (H) is not a list (i.e., it's an atom, number, or variable), it's already "flat," so we just include it directly in the FlatList and continue flattening the Tail. \+ is_list(H) is crucial here to ensure this clause only fires for non-list elements.
Queries:
?- flatten_list([1, [2, 3], 4], Flat).
Flat = [1, 2, 3, 4].
?- flatten_list([[a, b], [c, [d, e]]], Flat).
Flat = [a, b, c, d, e].
?- flatten_list([], Flat).
Flat = [].
?- flatten_list([a, b, c], Flat). % Already flat
Flat = [a, b, c].
SWI-Prolog Built-in for Flattening:
SWI-Prolog actually has a built-in flatten/2 predicate that performs this exact operation:
?- flatten([a, b, [c, d], e], Flat).
Flat = [a, b, c, d, e].
?- flatten([[1, 2], [3, [4, 5]]], Flat).
Flat = [1, 2, 3, 4, 5].
While it's good to know the built-in, implementing it yourself is a fantastic way to understand Prolog's recursive nature.
3. Counting Elements (nested length/2 or count_elements/2)
Counting all "leaf" elements in a nested list.
% count_nested_elements(NestedList, Count)
% Base case: Empty list has 0 elements.
count_nested_elements([], 0).
% Recursive case 1: Head is a list. Sum counts from head and tail.
count_nested_elements([H|T], Count) :-
is_list(H),
count_nested_elements(H, CountH),
count_nested_elements(T, CountT),
Count is CountH + CountT.
% Recursive case 2: Head is not a list. Count it as 1 and add to tail count.
count_nested_elements([_H|T], Count) :-
\+ is_list(_H),
count_nested_elements(T, CountT),
Count is 1 + CountT.
Queries:
?- count_nested_elements([a, b, [c, d], e], Count).
Count = 5.
?- count_nested_elements([[1, 2], [3, [4, 5]]], Count).
Count = 5.
?- count_nested_elements([], Count).
Count = 0.
?- count_nested_elements([a, [b, []], c], Count). % Note: [] counts as 0 elements.
Count = 3.
4. Mapping over Nested Lists (applying a function to each non-list element)
This is more complex as you might want to preserve the structure.
% map_nested_elements(Predicate, NestedList, MappedList)
% Predicate should be a callable term, e.g., 'double' or 'square'
% Predicate will be called as Predicate(In, Out)
% Base case: empty list maps to empty list
map_nested_elements(_, [], []).
% Recursive case 1: Head is a list. Recurse into the head.
map_nested_elements(Predicate, [H|T], [MappedH|MappedT]) :-
is_list(H),
map_nested_elements(Predicate, H, MappedH),
map_nested_elements(Predicate, T, MappedT).
% Recursive case 2: Head is not a list. Apply the predicate to the head.
map_nested_elements(Predicate, [H|T], [MappedH|MappedT]) :-
\+ is_list(H),
call(Predicate, H, MappedH), % Call the provided predicate on H
map_nested_elements(Predicate, T, MappedT).
% Example predicate: Double a number
double(X, Y) :- Y is X * 2.
% Example predicate: Capitalize an atom (requires atom_codes/2, upcase_atom/2, etc.)
% For simplicity, let's just make one up for demonstration:
capitalize(Atom, Capitalized) :-
atom_concat('CAP_', Atom, Capitalized).
Queries:
?- map_nested_elements(double, [1, [2, 3], 4], Result).
Result = [2, [4, 6], 8].
?- map_nested_elements(capitalize, [a, [b, [c]], d], Result).
Result = [CAP_a, [CAP_b, [CAP_c]], CAP_d].
Key Takeaways for Nested Lists
is_list/1 is your best friend: Always use it to distinguish between a regular element and a sub-list.
- Recursion is fundamental: You'll almost always need at least two recursive clauses: one for when the head is a list, and one for when it's not.
- Base Cases are Critical: Ensure you have a non-recursive clause for
[] (the empty list) to stop the recursion.
- Think Declaratively: Describe what an operation means for an empty list, for a list whose head is a simple element, and for a list whose head is another list. Prolog will figure out the how.
With these concepts, you can handle a wide variety of operations on nested list structures in SWI-Prolog.