Elixir type syntax examples

A reference to some Elixir language syntax for types. Remember that Elixir data structures are all immutable.

Atoms

Leading semicolon

:white
:black
:red
:ok
:error

Boolean values true and false are atoms :true and :false. The same for nil and :nil.

Linked List

Square brackets

[ 1, 2, 3 ]
[ "foo", "bar" ]
[ 10, "x", true ]

Common functions and operators:

Function or OperatorResult
length([ "x", "y" ])2
[1, 2] ++ [3, 4, 5][1, 2, 3, 4, 5]
[1, 2, 3, 4] -- [2, 4][1, 3]
hd([1, 2, 3, 4])1
tl([1, 2, 3, 4])[2, 3, 4]

Tuples

Curly brackets

{ :error, "Error message" }
{ 1, 2, 3 }
{ true, false, "text"}
{ true, true, "One", "One" }

Common functions:

FunctionResult
elem({ :ok, "OK" }, 1)"OK"
put_elem({ "first", "third" }, 1, "second"){"first", "second"}

Other functions are in the Tuple module, for example:

FunctionResult
Tuple.append({ 1, 2, 3 }, 4){1, 2, 3, 4}
Tuple.insert_at({1, 2, 3}, 1, 1.5){1, 1.5, 2, 3}
Tuple.delete_at({1, 2, 3}, 1){1, 3}

Keyword list

List of tuples with two values and the first one is an atom. A simple key-map data structure. The keys are atoms, ordered and can be duplicated.

 [ { :k1, 1 }, { :k2, 2 } ]

Special syntax:

[ k1: 1, k2: 2 ]

See the correct place for the semicolon, from :k1 to k1:

To access a key you can use square brackets:

tl = [ first: "first", second: "second" ]
tl[:first]
# The result is: "first"

When a KL is used as the last argument of a function, the square brackets are optional:

example_fun first_param, k1: 1, k2: 2
example_fun(first_param, k1: 1, k2: 2)
example_fun(first_param, [ k1: 1, k2: 2 ])
example_fun(first_param, [ { :k1, 1 }, { :k2, 2 } ])

To manipulate a KL there is the Keyword module but remember that they are lists.

Maps

The real key-map data structure in Elixir.

# Standard syntax
map = %{ :k => 1, 100 => "one hundred" }

# If all the keys are atoms
map2 = %{ k1: 1, k2: 2 }

# Syntax error
map3 = %{ k1: 1, :k2 => 2 }

The :k atom and the number 100 are the keys; the number 1 and one hundred are the values.

OperationResult
map[:k]1
map[100]"one hundred"
%{ map | :k => "ten" }%{100 => "one hundred", :k => "ten"}
%{ map | :not_exists => "..." }(KeyError) key :not_exists not found
map.k1
map2.k22