I wrote a tail-recursive list-flattening function, but I'm not too happy with it.
a) Is tail-recursion necessary here, or will the function be optimized without it?
b) It's ugly how many clauses there are, and that I have to call out to flatten
in the expression of the first clause of flatten_acc
So, how could I do better?
(To be clear, this is a function that completely flattens the list -- e.g. flatten([foo, [[[bar]], [baz]]])
== [foo, bar, baz]
)
flatten(List) ->
lists:reverse(flatten_acc(List, [])).
flatten_acc([[[H|T0]|T1]|T2], Acc) ->
flatten_acc([flatten([[H|T0]|T1])|T2], Acc);
flatten_acc([[H|T0]|T1], Acc) ->
flatten_acc([T0|T1], [H|Acc]);
flatten_acc([[]|T], Acc) ->
flatten_acc(T, Acc);
flatten_acc([H|T], Acc) ->
flatten_acc(T, [H|Acc]);
flatten_acc([], Acc) ->
Acc.
Thanks!