Erlang原子的简单解释

kokeuurv  于 2022-12-08  发布在  Erlang
关注(0)|答案(3)|浏览(134)

我正在学习Erlang,并试图理解原子的概念。我知道Python:用简单的术语或者用类似的Python来解释这些“原子”有什么好的解释呢?到目前为止,我的理解是类型就像字符串,但没有字符串操作?

ej83mcc0

ej83mcc01#

Docs say that:
An atom is a literal, a constant with name.
Sometimes you have couple of options, that you would like to choose from. In C for example, you have enum :

enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

In C, it is really an integer, but you can use it in code as one of options. Atoms in Erlang are very useful in pattern matching. Lets consider very simple server:

loop() ->
    receive
        {request_type_1, Request} ->
            handle_request_1(Request),
            loop();
        {request_type_2, Request} ->
            handle_request_2(Request),
            loop();
        {stop, Reason} ->
            {ok, Reason};
        _ ->
            {error, bad_request}
    end.

Your server receives messages, that are two element tuples and uses atoms to differentiate between different types of requests: request_type_1 , request_type_2 and stop . It is called pattern matching.
Server also uses atoms as return values. ok atom means, that everything went ok. _ matches everything, so in case, that simple server receives something unexpected, it quits with tuple {error, Reason} , where the reason is also atom bad_request .
Boolean values true and false are also atoms. You can build logical functions using function clauses like this:

and(true, true) ->
    true;
and(_, _) ->
    false.

or(false, false) ->
    false;
or(_, _) ->
    true.

(It is a little bit oversimplified, because you can call it like this: or(atom1, atom2) and it will return true , but it is only for illustration.)
Module names in Erlang are also atoms, so you can bind module name to variable and call it, for example type this in Erlang shell:

io:format("asdf").
Variable = io.
Variable:format("asdf").

You should not use atoms as strings, because they are not garbage collected. If you start creating them dynamically, you can run out of memory. They should be only used, when there is fixed amount of options, that you type in code by hand. Of course, you can use the same atom as many times as you want, because it always points to the same point in memory (an atom table).
They are better than C enums, because the value is known at runtime. So while debugging C code, you would see 1 instead of Tuesday in debugger. Using atoms doesn't have that disadvantage, you will see tuesday in your both in your code and Erlang shell.

cig3rfwq

cig3rfwq2#

此外,它们还经常用于标记元组,以便于描述。例如:
{age,第四十二章}
而不仅仅是
42

ajsxfq5m

ajsxfq5m3#

Atom是文字常量。没有值,但可以用作值。示例如下:true,false,undefined.如果你想把它作为一个字符串来使用,你需要应用atom_to_list(atom)来得到一个字符串(list).模块名也是atom.看一下http://www.erlang.org/doc/reference_manual/data_types.html

相关问题