> Erlang中文手册 > flatten/1 将多层嵌套列表转为单层列表

lists:flatten/1

将多层嵌套列表转为单层列表

用法:

flatten(DeepList) -> List

内部实现:

 %% flatten(List)
%% flatten(List, Tail)
%%  Flatten a list, adding optional tail.

-spec flatten(DeepList) -> List when
      DeepList :: [term() | DeepList],
      List :: [term()].

flatten(List) when is_list(List) ->
    do_flatten(List, []).

do_flatten([H|T], Tail) when is_list(H) ->
    do_flatten(H, do_flatten(T, Tail));
do_flatten([H|T], Tail) ->
    [H|do_flatten(T, Tail)];
do_flatten([], Tail) ->
    Tail.

将多层嵌套列表转为一个单层列表

lists:flatten([[1], [2], 3, [4, [5, 6, [7, 8]]]]).
Term = {1, a, [2, 3]},
lists:flatten(io_lib:format("~p", [Term])).