Erlang Thursday – lists:flatten/1

Today’s Erlang Thursday function is lists:flatten/1.

lists:flatten/1 flattens out an arbitrarily deep list of Erlang terms, into a “flattened” list.

% []
lists:flatten([a, b, c]).
% [a,b,c]
lists:flatten([a, b, [1, [x, y], 3], c]).
% [a,b,1,x,y,3,c]
lists:flatten([a, b, [1, [x, {some, tuple}], 3], c]).    
% [a,b,1,x,{some,tuple},3,c]

Be warned though, it flattens out all lists, as seen here

lists:flatten([a, "foo", b]).    
% [a,102,111,111,b]

You get the above lists with numbers in it, because under the covers, a string is just a list of integers, so you get the ASCII character codes for the letters f and o in "foo".

If you want the string to “remain”, you need to use the string as a binary type like this:

lists:flatten([a, <<"foo">>, b]).                       
% [a,<<"foo">>,b]

And as a bonus, there is also a lists:flatten/2, that takes a list to flatten, and another argument tail, which is the value to append to the newly flattened list.

lists:flatten([a, [1, [b, [2]]]], [x, y, z]).
% [a,1,b,2,x,y,z]


Leave a Reply

Your email address will not be published. Required fields are marked *