Understanding Erlang Syntax and Data Types

April 5, 2024

In this post, we delve into Erlang syntax and explore its data types, including atoms, numbers, tuples, lists, and binaries. We also discuss pattern matching and variable bindings in Erlang.

Erlang Syntax

Erlang has a simple and clean syntax that makes it easy to read and understand. Let’s take a look at some of the key aspects of Erlang syntax.

Atoms

An atom is a literal, a constant with a name. In Erlang, atoms are used to represent constants. An atom is written with a leading lowercase letter followed by a sequence of alphanumeric characters and underscores. For example:

atom_name.

Numbers

Erlang supports integers and floating-point numbers. Integers are written as sequences of numeric characters, optionally preceded by a minus sign. Floating-point numbers are written as sequences of numeric characters with a decimal point. For example:

42.
-3.14.

Tuples

A tuple is an ordered collection of elements. In Erlang, tuples are written within curly braces and elements are separated by commas. For example:

{element1, element2, element3}.

Lists

A list is a collection of elements where the length can vary. In Erlang, lists are written within square brackets and elements are separated by commas. For example:

[1, 2, 3, 4, 5].

Binaries

Erlang also supports binaries, which are sequences of bytes. Binaries are written using the <<> syntax. For example:

<<1, 2, 3, 4>>.

Pattern Matching and Variable Bindings

Pattern matching is a powerful feature in Erlang that allows you to match and destructure data structures. Variable bindings are used to capture values during pattern matching. Let’s see an example of pattern matching and variable bindings:

case {1, 2, 3} of
    {A, B, C} -> io:format("A = ~p, B = ~p, C = ~p", [A, B, C])
end.

In this example, the tuple {1, 2, 3} is matched against the pattern {A, B, C}, and the variables A, B, and C are bound to the corresponding values. The io:format function then prints the values of A, B, and C.