Search code examples
listnestedprologswi-prolog

Get elements of arbitrary nested lists


I am looking for some predicate in SWI-Prolog to get the elements of some arbitrary nested list. Means, if I e.g. have the list:

L = [[a,b], c, [d, [e, f]]]

I get as result:

R = [a,b,c,d,e,f]

Solution

  • As @brebs mentioned in his comment, Use predefined predicate flatten/2

    % ?- flatten([[a,b], c, [d, [e, f]]], R).
    %     R = [a, b, c, d, e, f]
    

    This user-defined implementation is similar to the predefined one [1]

    my_flatten([],[]).
    my_flatten([H|T], [H|Res]) :- \+ is_list(H), my_flatten(T, Res), !.
    my_flatten([H|T], Res) :- my_flatten(H, Res). % H is list.
    

    [1] except for cases of non-termination like my_flatten(X,non_list). and like my_flatten([X],[1,2,3,4]). thanks to @false comment