LoginSignup
4
2

More than 5 years have passed since last update.

Elixir Atoms

Last updated at Posted at 2014-10-19

Elixir Atoms

概要

Elixir の Atoms について。

Atom は 特定の名前を持つ定数の一種です。
コロンに続けて文字列名か、オペレータ名を続けて定義します。
コロンに続けて直接文字列を指定する場合は、
Atom は文字・数字・アンダースコア・@ を利用できます。
最後はエクスクラメーションマークかクエスチョンマークで終えることもできます。

コロンに続けてシングルォート・ダブルクォートで名前を指定する場合は
ASCII 範囲の文字を利用可能です。
※下記公式ドキュメントより

Currently Elixir does not support conversions from strings which contains Unicode codepoints greater than 0xFF.

Atom の値は名前であり、同じ名前の Atom は等価です。

コロンに続けて直接名前を指定した場合

iex> :text
:text
iex> :_
:_
iex> :hoge!
:hoge!
iex> :hoge?
:hoge?
iex> :a123
:a123
iex> :a@
:a@
iex> :a@b
:a@b
iex> :+
:+
iex> :<>
:<>
iex> :hoge == :hoge
true
iex> :hoge == :hige
false

コロンに続けてダブルクォートで名前を指定した場合

iex> ascii_atoms = 0..127 |> Enum.map(&("a" <> <<&1>> <> "b")) |> Enum.map(&(String.to_atom(&1)))
[:"a\0b", :"a\x01b", :"a\x02b", :"a\x03b", :"a\x04b", :"a\x05b", :"a\x06b",
 :"a\ab", :"a\bb", :"a\tb", :"a\nb", :"a\vb", :"a\fb", :"a\rb", :"a\x0Eb",
 :"a\x0Fb", :"a\x10b", :"a\x11b", :"a\x12b", :"a\x13b", :"a\x14b", :"a\x15b",
 :"a\x16b", :"a\x17b", :"a\x18b", :"a\x19b", :"a\x1Ab", :"a\eb", :"a\x1Cb",
 :"a\x1Db", :"a\x1Eb", :"a\x1Fb", :"a b", :"a!b", :"a\"b", :"a#b", :"a$b",
 :"a%b", :"a&b", :"a'b", :"a(b", :"a)b", :"a*b", :"a+b", :"a,b", :"a-b", :"a.b",
 :"a/b", :a0b, :a1b, ...]

iex> ascii_atoms |> Enum.take(10)
[:"a\0b", :"a\x01b", :"a\x02b", :"a\x03b", :"a\x04b", :"a\x05b", :"a\x06b",
 :"a\ab", :"a\bb", :"a\tb"]

iex> Enum.slice(ascii_atoms, 65, 26)
[:aAb, :aBb, :aCb, :aDb, :aEb, :aFb, :aGb, :aHb, :aIb, :aJb, :aKb, :aLb, :aMb,
 :aNb, :aOb, :aPb, :aQb, :aRb, :aSb, :aTb, :aUb, :aVb, :aWb, :aXb, :aYb, :aZb]

組み込み関数

下記を参照
http://elixir-lang.org/docs/stable/elixir/Atom.html

to_char_list(atom)

Atom を char_list に変換します

iex> Atom.to_char_list(:hoge)
'hoge'

to_string(atom)

Atom を string に変換します

iex> Atom.to_string(:hoge)
"hoge"

参照

4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2