menico
menico

Reputation: 23

Affix a string to items within a lists:flatten in Erlang?

I have a list like this one ['a','b','c','d'] and what I need is to add a affix to each item in that list like : ['a@erlang','b@erlang','c@erlang','d@erlang']

I tried using 1lists:foreach1 and then concat two strings to one and then lists:append to the main list, but that didn't work for me.

Example of what I tried:

LISTa = [],
lists:foreach(fun (Item) ->
    LISTa = lists:append([Item,<<"@erlang">>])
 end,['a','b','c','d'])

Thanks in advance.

Upvotes: 2

Views: 72

Answers (2)

BlackMamba
BlackMamba

Reputation: 10252

1> L = ['a','b','c','d'].
[a,b,c,d]
2> [ list_to_atom(atom_to_list(X) ++ "@erlang") ||X <- L]. 
[a@erlang,b@erlang,c@erlang,d@erlang]

Please try this code, you can use list_to_atom and atom_to_list.

Upvotes: 1

user4695271
user4695271

Reputation:

This will do the trick (using list comprehensions):

1> L = ["a","b","c","d"].
["a","b","c","d"]
2> R = [X ++ "@erlang" || X <- L].
["a@erlang","b@erlang","c@erlang","d@erlang"]
3>

Notice that I changed the atoms for strings; It's discouraged to "create atoms on the fly/dynamically" in Erlang, so I have that framed in my mind. If you still need so, change the implementation a little bit and you are good to go.

NOTE: I'm assuming the concatenation between atoms and binaries is, somehow, something you did not do on purpose.

Upvotes: 0

Related Questions