Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang : flattening a list of strings

I have a list like this:

[["str1","str2"],["str3","str4"],["str5","str6"]]

And I need to convert it to

["str1", "str2", "str3", "str4", "str5", "str6"]

How do I do this?

The problem is that I'm dealing with lists of strings, so when I do

lists:flatten([["str1","str2"],["str3","str4"],["str5","str6"]])

I get

"str1str2str3str4str5str6"

However, if the elements of the original list where just atoms, then lists:flatten would have given me what I needed. How do I achieve the same with strings?

like image 884
ErJab Avatar asked May 26 '10 08:05

ErJab


3 Answers

lists:append does exactly what you need:

1> lists:append([["str1","str2"],["str3","str4"],["str5","str6"]]).
["str1","str2","str3","str4","str5","str6"]

(lists:concat does the right thing, but threatens to do some type conversion too.)

like image 171
cthulahoops Avatar answered Oct 19 '22 19:10

cthulahoops


If your list is always a "list of list of string", then you can simply use the foldl operator, with something like:

Flat = list:foldl(fun(X, Acc) -> X ++ Acc end, [], List)

In the case your list nesting can be of arbitrary depth, I would rather suggest to let erlang know your strings are not mere character lists, using an encoding such as:

[[{string, "str1"},{string, "str2"}],
 [{string, "str3"}, {string, "str4"}],
 [{string, "str5"},{string, "str6"}]]

This way, list:flatten will do the right thing, and give:

[{string, "str1"},{string, "str2"},
 {string, "str3"}, {string, "str4"},
 {string, "str5"},{string, "str6"}]

which you can convert back if needed to a raw list of strings using foldl. If your strings are to be handled differently from mere character lists, then they probably deserve to be a real data structure, see this blog entry for an interesting discussion on this matter.

like image 2
tonio Avatar answered Oct 19 '22 19:10

tonio


lists:concat/1 works...

like image 1
mwt Avatar answered Oct 19 '22 18:10

mwt