[erlang-questions] how: Another library flatten function?

Richard O'Keefe ok@REDACTED
Sun Feb 28 22:50:54 CET 2010


On Feb 27, 2010, at 2:58 AM, Bengt Kleberg wrote:

> Greetings,
>
> I have the following list: ["asd",[["Flow","kalle"]],["Sub","F"]]
> I would like to flatten it to: ["asd","Flow","kalle","Sub","F"]
> lists:flatten/1 is too effective. It gives me: "asdFlowkalleSubF"
>
> Is there another flatten somewhere?

The general form of flatten is going to be

flatten(X) ->
     flatten_loop(X, []).

flatten_loop(X, L) when base_case(X) ->
     [X|L];
flatten_loop([], L) ->
     L;
flatten_loop([H|T], L) ->
     flatten_loop(H, flatten_loop(T, L)).

where the first clause of flatten_loop/2 isn't legal Erlang.

The question of interest is "what exactly is the base case"?

If all the strings are non-empty, it's not hard:

flatten_string_list(X) ->
    flatten_string_list_loop(X, []).

flatten_string_list_loop(X = [H|_], L) when is_integer(H) ->
     [X|L];
flatten_string_list_loop(X, L) when is_binary(X) ->
     [X|L];
flatten_string_list_loop([H|T], L) ->
     flatten_string_list_loop(H,
         flatten_string_list_loop(T, L));
flatten_string_list_loop([], L) ->
     L.

and we let anything else crash.

Allowing empty strings would make the code rather trickier to
develop, although not impossible.  I think before looking for
another flatten, the task is to specify what you actually want.



More information about the erlang-questions mailing list