Erlang -- Data Types

User's Guide
PDF
Top

Erlang Reference Manual
User's Guide
Version 5.8.3

Expand All
Contract All

Chapters

- Introduction
  - Top of chapter
  - Purpose
  - Prerequisites
  - Document Conventions
  - Complete List of BIFs
  - Reserved Words
  - Character Set
- Data Types
  - Top of chapter
  - Terms
  - Number
  - Atom
  - Bit Strings and Binaries
  - Reference
  - Fun
  - Port Identifier
  - Pid
  - Tuple
  - List
  - String
  - Record
  - Boolean
  - Escape Sequences
  - Type Conversions
- Pattern Matching
  - Top of chapter
  - Pattern Matching
- Modules
  - Top of chapter
  - Module Syntax
  - Module Attributes
  - Comments
  - The module_info/0 and module_info/1 functions
- Functions
  - Top of chapter
  - Function Declaration Syntax
  - Function Evaluation
  - Tail recursion
  - Built-In Functions, BIFs
- Types and Function Specifications
  - Top of chapter
  - Introduction of Types
  - Types and their Syntax
  - Type declarations of user-defined types
  - Type information in record declarations
  - Specifications for functions
- Expressions
  - Top of chapter
  - Expression Evaluation
  - Terms
  - Variables
  - Patterns
  - Match
  - Function Calls
  - If
  - Case
  - Send
  - Receive
  - Term Comparisons
  - Arithmetic Expressions
  - Boolean Expressions
  - Short-Circuit Expressions
  - List Operations
  - Bit Syntax Expressions
  - Fun Expressions
  - Catch and Throw
  - Try
  - Parenthesized Expressions
  - Block Expressions
  - List Comprehensions
  - Bit String Comprehensions
  - Guard Sequences
  - Operator Precedence
- The Preprocessor
  - Top of chapter
  - File Inclusion
  - Defining and Using Macros
  - Predefined Macros
  - Macros Overloading
  - Flow Control in Macros
  - Stringifying Macro Arguments
- Records
  - Top of chapter
  - Defining Records
  - Creating Records
  - Accessing Record Fields
  - Updating Records
  - Records in Guards
  - Records in Patterns
  - Nested records
  - Internal Representation of Records
- Errors and Error Handling
  - Top of chapter
  - Terminology
  - Exceptions
  - Handling of Run-Time Errors in Erlang
  - Exit Reasons
- Processes
  - Top of chapter
  - Processes
  - Process Creation
  - Registered Processes
  - Process Termination
  - Message Sending
  - Links
  - Error Handling
  - Monitors
  - Process Dictionary
- Distributed Erlang
  - Top of chapter
  - Distributed Erlang System
  - Nodes
  - Node Connections
  - epmd
  - Hidden Nodes
  - C Nodes
  - Security
  - Distribution BIFs
  - Distribution Command Line Flags
  - Distribution Modules
- Compilation and Code Loading
  - Top of chapter
  - Compilation
  - Code Loading
  - Code Replacement
  - Running a function when a module is loaded
- Ports and Port Drivers
  - Top of chapter
  - Ports
  - Port Drivers
  - Port BIFs

# 2 Data Types

### 2.1 Terms

Erlang provides a number of data types which are listed in this chapter. A piece of data of any data type is called a term.

### 2.2 Number

There are two types of numeric literals, integers and floats. Besides the conventional notation, there are two Erlang-specific notations:

- $char
  ASCII value of the character char.
- base#value
  Integer with the base base, which must be an integer in the range 2..36.
  In Erlang 5.2/OTP R9B and earlier versions, the allowed range is 2..16.

Examples:

    1> 42.
    42
    2> $A.
    65
    3> $\n.
    10
    4> 2#101.
    5
    5> 16#1f.
    31
    6> 2.3.
    2.3
    7> 2.3e3.
    2.3e3
    8> 2.3e-3.
    0.0023

### 2.3 Atom

An atom is a literal, a constant with name. An atom should be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

Examples:

    hello
    phone_number
    'Monday'
    'phone number'

### 2.4 Bit Strings and Binaries

A bit string is used to store an area of untyped memory.

Bit Strings are expressed using the bit syntax.

Bit Strings which consists of a number of bits which is evenly divisible by eight are called Binaries

Examples:

    1> <<10,20>>.
    <<10,20>>
    2> <<"ABC">>.
    <<"ABC">>
    1> <<1:1,0:1>>.
    <<2:2>>

More examples can be found in Programming Examples.

### 2.5 Reference

A reference is a term which is unique in an Erlang runtime system, created by calling make_ref/0.

### 2.6 Fun

A fun is a functional object. Funs make it possible to create an anonymous function and pass the function itself -- not its name -- as argument to other functions.

Example:

    1> Fun1 = fun (X) -> X+1 end.
    #Fun<erl_eval.6.39074546>
    2> Fun1(2).
    3

Read more about funs in Fun Expressions. More examples can be found in Programming Examples.

### 2.7 Port Identifier

A port identifier identifies an Erlang port. open_port/2, which is used to create ports, will return a value of this type.

Read more about ports in Ports and Port Drivers.

### 2.8 Pid

A process identifier, pid, identifies a process. spawn/1,2,3,4, spawn_link/1,2,3,4 and spawn_opt/4, which are used to create processes, return values of this type. Example:

    1> spawn(m, f, []).
    <0.51.0>

The BIF self() returns the pid of the calling process. Example:

    -module(m).
    -export([loop/0]).

    loop() ->
        receive
            who_are_you ->
                io:format("I am ~p~n", [self()]),
                loop()
        end.

    1> P = spawn(m, loop, []).
    <0.58.0>
    2> P ! who_are_you.
    I am <0.58.0>
    who_are_you

Read more about processes in Processes.

### 2.9 Tuple

Compound data type with a fixed number of terms:

    {Term1,...,TermN}

Each term Term in the tuple is called an element. The number of elements is said to be the size of the tuple.

There exists a number of BIFs to manipulate tuples.

Examples:

    1> P = {adam,24,{july,29}}.
    {adam,24,{july,29}}
    2> element(1,P).
    adam
    3> element(3,P).
    {july,29}
    4> P2 = setelement(2,P,25).
    {adam,25,{july,29}}
    5> tuple_size(P).
    3
    6> tuple_size({}).
    0

### 2.10 List

Compound data type with a variable number of terms.

    [Term1,...,TermN]

Each term Term in the list is called an element. The number of elements is said to be the length of the list.

Formally, a list is either the empty list [] or consists of a head (first element) and a tail (remainder of the list) which is also a list. The latter can be expressed as [H|T]. The notation [Term1,...,TermN] above is actually shorthand for the list [Term1|[...|[TermN|[]]]].

Example:
[] is a list, thus
[c|[]] is a list, thus
[b|[c|[]]] is a list, thus
[a|[b|[c|[]]]] is a list, or in short [a,b,c].

A list where the tail is a list is sometimes called a proper list. It is allowed to have a list where the tail is not a list, for example [a|b]. However, this type of list is of little practical use.

Examples:

    1> L1 = [a,2,{c,4}].
    [a,2,{c,4}]
    2> [H|T] = L1.
    [a,2,{c,4}]
    3> H.
    a
    4> T.
    [2,{c,4}]
    5> L2 = [d|T].
    [d,2,{c,4}]
    6> length(L1).
    3
    7> length([]).
    0

A collection of list processing functions can be found in the STDLIB module lists.

### 2.11 String

Strings are enclosed in double quotes ("), but is not a data type in Erlang. Instead a string "hello" is shorthand for the list [$h,$e,$l,$l,$o], that is [104,101,108,108,111].

Two adjacent string literals are concatenated into one. This is done at compile-time and does not incur any runtime overhead. Example:

    "string" "42"

is equivalent to

    "string42"

### 2.12 Record

A record is a data structure for storing a fixed number of elements. It has named fields and is similar to a struct in C. However, record is not a true data type. Instead record expressions are translated to tuple expressions during compilation. Therefore, record expressions are not understood by the shell unless special actions are taken. See shell(3) for details.

Examples:

    -module(person).
    -export([new/2]).

    -record(person, {name, age}).

    new(Name, Age) ->
        #person{name=Name, age=Age}.

    1> person:new(ernie, 44).
    {person,ernie,44}

Read more about records in Records. More examples can be found in Programming Examples.

### 2.13 Boolean

There is no Boolean data type in Erlang. Instead the atoms true and false are used to denote Boolean values.

Examples:

    1> 2 =< 3.
    true
    2> true or false.
    true

### 2.14 Escape Sequences

Within strings and quoted atoms, the following escape sequences are recognized:

Sequence | Description
\b | backspace
\d | delete
\e | escape
\f | form feed
\n | newline
\r | carriage return
\s | space
\t | tab
\v | vertical tab
\XYZ, \YZ, \Z | character with octal representation XYZ, YZ or Z
\xXY | character with hexadecimal representation XY
\x{X...} | character with hexadecimal representation; X... is one or more hexadecimal characters
\^a...\^z \^A...\^Z | control A to control Z
\' | single quote
\" | double quote
\\ | backslash

Table 2.1: Recognized Escape Sequences.

### 2.15 Type Conversions

There are a number of BIFs for type conversions. Examples:

    1> atom_to_list(hello).
    "hello"
    2> list_to_atom("hello").
    hello
    3> binary_to_list(<<"hello">>).
    "hello"
    4> binary_to_list(<<104,101,108,108,111>>).
    "hello"
    5> list_to_binary("hello").
    <<104,101,108,108,111>>
    6> float_to_list(7.0).
    "7.00000000000000000000e+00"
    7> list_to_float("7.000e+00").
    7.0
    8> integer_to_list(77).
    "77"
    9> list_to_integer("77").
    77
    10> tuple_to_list({a,b,c}).
    [a,b,c]
    11> list_to_tuple([a,b,c]).
    {a,b,c}
    12> term_to_binary({a,b,c}).
    <<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>
    13> binary_to_term(<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>).
    {a,b,c}