evnu
evnu

Reputation: 6680

Convert Integer to Atom in Elixir

In Erlang, one can write '1' to get an integer-named atom. Elixir uses the syntax :<name> to define an atom, but :1 is not possible:

iex(1)> :1
** (SyntaxError) iex:1: unexpected token: ":" (column 1, codepoint U+003A)

Is there a way in Elixir to generate an integer-named atom?

Upvotes: 1

Views: 3234

Answers (3)

Christopher Milne
Christopher Milne

Reputation: 938

You can also leverage string interpolation:
String.to_atom("#{your_number}")

Upvotes: 5

Dogbert
Dogbert

Reputation: 222158

You can put the 1 in quotes and prepend : to get the equivalent of '1' in Erlang:

iex(1)> :"1"
:"1"
iex(2)> :'1'
:"1"

Upvotes: 7

PatNowak
PatNowak

Reputation: 5812

Answer provided by Dogbert is the simplest one. If you would like to use functions for that unfortunately there's no function for that. You can do it via converting int first to the Sting and then to the Atom.

1
|> Integer.to_string()
|> String.to_atom()
# :"1"

Upvotes: 5

Related Questions