Create a simple anonymous function that concatenates two lists of atoms

I’m new to Elixir and I’m trying to create a simple anonymous function that concatenates two lists of atoms.

Correctly, the code written is:
iex (1) >list_concat = fn[:a,:b], [:c,:d] -> [:a,:b,:c,:d] end
iex (2) >list_concat.([:1,:2],[:3,:4])
iex throws the following error
** (SyntaxError) iex:40: unexpected token: “:” (column 17, codepoint U+003A)
Anyone help to understand and unblock me?

1 Like
iex(1)> [:a] ++ [:b, :c] 
[:a, :b, :c]
iex(2)> [:"1"] ++ [:"2", :"3"]
[:"1", :"2", :"3"]

Use ++ (or --) to concat 2 lists

fn list1, list2 -> list1 ++ list2 end
3 Likes

An atom that is just a number needs to be quoted :slight_smile: :"1"

2 Likes

Welcome to the forum!

http://erlang.org/doc/reference_manual/data_types.html#atom

3.3 Atom

An atom is a literal, a constant with name. An atom is to be enclosed in single quotes (’) if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

iex(42)> String.to_existing_atom("1")    
:"1"
iex(43)> String.to_existing_atom("EXIT")
:EXIT
iex(44)> String.to_existing_atom("error")
:error
iex(45)> String.to_existing_atom("nil")  
nil
iex(46)> String.to_existing_atom("true")
true
iex(47)> String.to_existing_atom("false")
false

String.to_existing_atom/1
String.to_atom/1

Warning: this function creates atoms dynamically and atoms are not garbage-collected. Therefore, string should not be an untrusted value, such as input received from a socket or during a web request.

3 Likes