📜  Erlang-Atoms(1)

📅  最后修改于: 2023-12-03 14:41:00.009000             🧑  作者: Mango

Erlang Atoms

Introduction

In Erlang, an atom is a constant with a name. Atoms are used to represent fixed values in the code. They are typically used as labels, module names, and status indicators. Atoms are unique and their names are stored in a global atom table, which allows for efficient comparison and pattern matching.

Creating Atoms

To create an atom, you simply write a sequence of characters enclosed in single quotes. For example:

'hello'
'world'

In this case, 'hello' and 'world' are atoms.

Usage

Atoms are frequently used in pattern matching and control flow constructs in Erlang. They are commonly used as tags to indicate the state of a process or a message. For example, consider a simple message passing scenario:

receive
    {message, 'hello'} ->
        io:format("Received hello message.~n");
    {message, 'world'} ->
        io:format("Received world message.~n");
    _ ->
        io:format("Received unknown message.~n")
end.

Here, we pattern match on the atom 'hello' and 'world' to handle specific message types.

Atom Comparison

Atoms are compared using a lexicographic ordering. The comparison is based on the position of the characters in the ASCII table. For example, 'hello' is less than 'world' in the atom comparison.

Atom Table

Erlang maintains a global atom table, where atom names are stored. The atom table ensures that each atom is represented by only one instance in memory, making atom comparison very efficient.

Common Atoms

Erlang has some built-in atoms, such as true, false, and undefined, which represent boolean and undefined values. Additionally, there are convenience atoms such as ok, error, and badarg used for indicating the status of operations.

Pattern Matching with Atoms

Atoms play a central role in pattern matching in Erlang. By using atoms in pattern matching, you can easily distinguish between different states and handle messages accordingly. This pattern matching capability is often used in concurrent programming and message passing scenarios.

Summary

In summary, atoms in Erlang are constants with names. They are used to represent fixed values, labels, module names, and status indicators. Atoms allow for efficient comparison and pattern matching, making them essential in concurrent and distributed Erlang programming.