Atoms are guaranteed to be unique and integral, in contrast to, e. g., floating-point constant values, which can differ because of inaccuracy while you're encoding, sending them over the wire, decoding on the other side and converting back to floating point. No matter what version of interpreter you're using, it ensures that atom has always the same "value" and is unique.
The Erlang VM stores all the atoms defined in all the modules in a global atom table.
There's no Boolean data type in Erlang. Instead the atoms true
and false
are used to denote Boolean values. This prevents one from doing such kind of nasty thing:
#define TRUE FALSE //Happy debugging suckers
In Erlang, you can save atoms to files, read them back, pass them over the wire between remote Erlang VMs etc.
Just as example I'll save a couple of terms into a file, and then read them back. This is the Erlang source file lib_misc.erl
(or its most interesting part for us now):
-module(lib_misc).
-export([unconsult/2, consult/1]).
unconsult(File, L) ->
{ok, S} = file:open(File, write),
lists:foreach(fun(X) -> io:format(S, "~p.~n",[X]) end, L),
file:close(S).
consult(File) ->
case file:open(File, read) of
{ok, S} ->
Val = consult1(S),
file:close(S),
{ok, Val};
{error, Why} ->
{error, Why}
end.
consult1(S) ->
case io:read(S, '') of
{ok, Term} -> [Term|consult1(S)];
eof -> [];
Error -> Error
end.
Now I'll compile this module and save some terms to a file:
1> c(lib_misc).
{ok,lib_misc}
2> lib_misc:unconsult("./erlang.terms", [42, "moo", erlang_atom]).
ok
3>
In the file erlang.terms
we'll get this contents:
42.
"moo".
erlang_atom.
Now let's read it back:
3> {ok, [_, _, SomeAtom]} = lib_misc:consult("./erlang.terms").
{ok,[42,"moo",erlang_atom]}
4> is_atom(SomeAtom).
true
5>
You see that the data is successfully read from the file and the variable SomeAtom
really holds an atom erlang_atom
.
lib_misc.erl
contents are excerpted from "Programming Erlang: Software for a Concurrent World" by Joe Armstrong, published by The Pragmatic Bookshelf. The rest source code is here.