Kabie
Kabie

Reputation: 10663

How to know if an atom or string is a valid identifier

Is there anything like Python's str.isidentifier:

>>> "foo".isidentifier()
True
>>> "42".isidentifier()
False

Upvotes: 2

Views: 1058

Answers (2)

legoscia
legoscia

Reputation: 41568

Any atom is a valid "identifier", in that it can be the name of a function, in both Erlang and Elixir. However, since some atoms need to be quoted, you might need some tricks to actually define such a function.

In Erlang, quoting the reference manual:

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 @.

I couldn't find a similar description for Elixir, but I presume it's similar.

This blog post addresses how to create such functions. In short, in Erlang you just put the function name in single quotes, and you're done:

-module(fortytwo).

-export(['42'/1]).

'42'(X) ->
    {ok, X}.

This function can be called like this from the shell:

> fortytwo:'42'(a).
{ok,a}

In Elixir, you need to use the unquote macro to define the function:

defmodule Fortytwo do
  def unquote(:"42")(x) do
    {:ok, x}
  end
end

And there is no way to quote the function name in a normal function call, so you need to use apply:

> apply(Fortytwo, :"42", [:a])
{:ok, :a}

Upvotes: 4

hyun
hyun

Reputation: 2143

In Erlang, atoms are used to represent constant values.

Erlang/OTP 18 [erts-7.0] [source] [64-bit] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V7.0  (abort with ^G)
1> is_atom(sunday).
true
2> is_atom('sunday').
true
3> is_atom("sunday").
false
4> 

And, there is no string type in erlang. string is just a list of integers.

8> B = [115,117,110,100,97,121].
"sunday"
9> is_list(B).
true
10> 

Upvotes: 4

Related Questions