Appendix A. An Erlang Parts Catalog

Like every language, Erlang has drawers full of parts that are fun to peruse. These are a very few of the more common ones. For much much more, see http://bitly.com/10CiiKR.

Reserved Words

There are a few Erlang terms you can’t use outside of their intended context.

The Erlang compiler will wonder what you’re trying to do if you use certain keywords as atoms or function names. It will try to treat your atoms as if they were code, and you can get very strange errors. After all, you should be able to have something called band, right? Unfortunately, no. band is one of the reserved words.

Table A-2. Reserved words, which require careful use

after

and

andalso

band

begin

bnot

bor

bsl

bsr

bxor

case

catch

cond

div

end

fun

if

let

not

of

or

orelse

query

receive

rem

try

when

xor

For function names, the answer is simple: use something else. If you want to use these as atoms, however, you can. You just need to enclose the offending reserved word in single quotes: 'receive', for example.

While they aren’t reserved words, there are also a few atoms commonly used in return values. It’s probably best to use them only in circumstances where they’re normally expected.

Table A-3. Commonly used return value atoms
Atom Means

ok

Normal exit to a method. (Does not mean that whatever you asked for succeeded.)

error

Something went wrong. Typically accompanied by a larger explanation.

undefined

A value hasn’t been assigned yet. Common in record instances.

reply

A reply is included with some kind of return value.

noreply

No return value is included. A response of some sort may come, however, from other communication.

stop

Used in OTP to signal that a server should stop, and triggers the terminate function.

ignore

Returned by OTP supervisor process that can’t start a child.

Operators

Table A-4. Logical (Boolean) operators
Operator Description

and

logical and

or

logical or

xor

logical xor

not

unary logical not

The not operator is processed first.

andalso and orelse are also boolean operators for logical and and logical or, but they are short-circuit operators. If they don’t need to process all the possibilities in their arguments, they stop at the first one that gives them a definite answer.

Table A-5. Term comparison operators
Operator Description

==

equal to

/=

not equal to

=<

less than or equal to

<

less than

>=

greater than or equal to

>

greater than

=:=

exactly equal to

=/=

exactly not equal to

You can compare elements of different types in Erlang. The relationship of types from “least” to “greatest” is:

number < atom < reference < fun < port < pid < tuple < list < bit string

Within number, you can compare integers and floats except with the more specific =:= and =/= operators, both of which will return false when you compare numbers of different types.

You can also compare tuples even when they contain different numbers of values. Erlang will go through the tuples from left to right and evaluate on the first value that returns a clear answer.

Table A-6. Arithmetic operators
Operator Description

+

unary + (positive)

-

unary - (negative)

+

addition

-

subtraction

*

multiplication

/

floating point division

div

integer division

rem

integer remainder of X/Y

Table A-7. Binary operators
Operator Description

bnot

unary bitwise not

band

bitwise and

bor

bitwise or

bxor

arithmetic bitwise xor

bsl

arithmetic bitshift left

bsr

bitshift right

Table A-8. Operator precedence, from highest to lowest
Operator Associativity

:

#

Unary + - bnot not

/ * div rem band and

Left associative

+ - bor bxor bsl bsr or xor

Left associative

++ --

Right associative +

== /= =< < >= > =:= =/=+

andalso

orelse

= !

Right associative

catch

The highest priority operator in an expression is evaluated first. Erlang evaluates operators with the same priority by following associative paths. (Left associative operators go left to right, right associative operators go right to left.)

Guard Components

Erlang allows only a limited subset of functions and other features in guard expressions, going well beyond a “no side effects” rule to keep a simple subset of possibilities. The list of allowed components includes the following:

  • true

  • Other constants (regarded as false)

  • Term comparisons (Table A-5)

  • Arithmetic expressions (Tables A-6 and A-7)

  • Boolean expressions and short-circuit expressions (andalso and orelse)

  • The following functions: abs/1, bit_size/1, byte_size/1, element/2, float/1, hd/1, is_atom/1, is_binary/1, is_bitstring/1, is_boolean/1, is_float/1, is_function/1, is_function/2, is_integer/1, is_list/1, is_map/1, is_number/1, is_pid/1, is_port/1, is_record/2, is_record/3, is_reference/1, is_tuple/1, length/1, map_size/1, node/0, round/1, self/0, size/1, tl/1, trunc/1, tuple_size/1

Common Functions

Table A-9. Mathematical functions
Function Use

math:pi/0

The constant pi

math:sin/1

Sine

math:cos/1

Cosine

math:tan/1

Tangent

math:asin/1

Inverse sine (arcsine)

math:acos/1

Inverse cosine (arcosine)

math:atan/1

Inverse tangent (arctangent)

math:atan2/2

Arctangent that understands quadrants

math:sinh/1

Hyperbolic sine

math:cosh/1

Hyperbolic cosine

math:tanh/1

Hyperbolic tangent

math:asinh/1

Hyperbolic arcsine

math:acosh/1

Hyperbolic arccosine

math:atanh/1

Hyperbolic arctangent

math:exp/1

Exponential function

math:log/1

Natural logarithm (base e)

math:log10/1

Logarithm (base 10)

math:pow/2

First argument to the second argument power

math:sqrt/1

Square root

math:erf/1

Error function

math:erfc/1

Complementary error function

Arguments for all trigonometric functions are expressed in radians. To convert degrees to radians, divide by 180 and multiply by pi.

Warning

The erf/1 and erfc/1 functions may not be implemented in Windows. The Erlang documentation also warns more broadly that “Not all functions are implemented on all platforms,” but these come directly from the C language libraries.

Table A-10. Approachable higher-order functions for processing lists
function Returns Use

lists:foreach/2

ok

Side effects specified in function

lists:map/2

new list

Apply function to list values

lists:filter/2

subset

Creating list where function returns true

lists:all/2

boolean

Returns true if function true for all values, otherwise false

lists:any/2

boolean

Returns true if function true for any values, otherwise false

lists:takewhile/2

subset

Collects the head of the list until the function is true

lists:dropwhile/2

subset

Deletes the head of the list until the function is true

lists:foldl/3

accumulator

Passes function list value and accumulator, forward-through list

lists:foldr/3

accumulator

Passes function list value and accumulator, backward-through list

lists:partition/3

tuple of two lists

Split list based on function

Chapter 7 describes these in greater detail.

Strings and Formatting

Table A-11. Simple control sequences for io:format and error_logger functions
Sequence Produces

~p

Value, pretty-printed

~w

Value, no indentation

~s

Contents of a string

~c

ASCII character corresponding to a number

~tc

Unicode character corresponding to a number

~i

Ignores that item

~n

Newline (doesn’t reference argument list)

Table A-12. Escape sequences for strings
Sequence Produces

\"

double quote

\'

single quote

\\

backslash

\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 in hex

\x{X…}

characters in hex, where X… is one or more hexadecimal characters

^a…\^z or ^A…\^Z

control-A to control-Z

Table A-13. Common string-processing functions
Function Returns

string:len/1

Length of the string (traverses string, so slows with big ones)

length/1

Length of the string (traverses string, so slows with big ones)

string:concat/2

A single string containing the two parts from the arguments

lists:concat/1

A single string containing all the parts from the arguments

lists:append/1-2

A single string containing all the parts from the arguments

lists:nth/2

The character at the specified position

hd/1

First character of the string

string:chr/2

The position where the specified character first appears

string:str/2

The position of a substring in a string

string:substr/2-3

A segment from a string at a given position of a given length

string:sub_string/2-3

A segment from a string between two positions

string:tokens/2

A list of pieces from a string broken at the specified separators

string:join/2

A string made from the list of pieces with specified separators added

string:words/1-2

The number of words in the string

string:chars/2-3

A string that repeats a given character a given number of times

string:copies/2

A string that repeats a given string a given number of times

string:strip/1-3

A string with leading and/or trailing whitespace (or specified characters) removed

string:left/2-3

A string of a specified length, padded with spaces on the right if needed

string:right/2-3

A string of a specified length, padded with spaces on the left if needed

string:centre/2-3

A string of a specified length, padded with spaces on the left and right if needed

lists:reverse/1-2

A string in backwards order

string:to_float/1

The float contents of the string, plus leftovers, or an error tuple

string:to_integer/1

The integer contents of the string, plus leftovers, or an error tuple

string:to_lower/1

A version of the string with all uppercase (Latin-1) characters converted to lowercase

string:to_upper/1

A version of the string with all lowercase (Latin-1) characters converted to uppercase

integer_to_list/1-2

A string version of an integer, optionally in a specified base

float_to_list/1

A string version of a float

erlang:fun_to_list/1

A string version of a fun

list_to_atom/1

An atom version of a string

Note: I wrote a single wrapper module that assembles Erlang’s tools for working with strings into one place. For more, visit https://github.com/simonstl/erlang-simple-string.