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

lists:flatten/2

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

用法:

flatten(DeepList, Tail) -> List

内部实现:

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

flatten(List, Tail) when is_list(List), is_list(Tail) ->
    do_flatten(List, Tail).

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 一样,都是把多层嵌套列表转为单层列表,只是多了一个在后面加上的尾列表 Tail

Tail = [9, 10],
lists:flatten([[1], [2], 3, [4, [5, 6, [7, 8]]]], Tail).