Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Data Types

notebooks/02_data_types.livemd

Data Types

Atom

:error
{:error, reason} = {:error, "file not found"}
reason
{:ok, msg} = {:ok, "status 200 ok"}
msg

String & Code Points

# Strings are UTF-8 encoded
name = "Octallium"
name
is_binary(name)
msg = "Hello " <> name
"Hello " <> name = msg
name
<> = name
head
head == ?O
# Pattern Matching
<<"O", rest::binary>> = name
rest
<<"Oc", rest::binary>> = name
rest
# Specify Size
<> = name
head
# Char list
chars = 'Octallium'
chars
'hello ' ++ chars
is_list(chars)
# Codepoints
?a

Processes

my_pid = self()
my_pid
is_pid(my_pid)

Lists Are Not Lists - They are Linked List!!!

list = ["a", "b", "c"]
list[0]
Enum.at(list, 1)
[first, second, third] = list
second
[_, _, third] = ["a", "b", "c"]
third
hd(list)
tl(list)
[h | t] = list
h
t

Tuple

{a, b} = {1, 2}
{:reply, msg, state} = {:reply, "Octallium found!", ["Octallium", "Louis", "Chiko"]}
msg

Keyword List

data = [a: 1, b: 2, c: 3]
[{:a, 1}] == [a: 1]
data[:c]

Maps

my_map = %{a: 1, b: 2, c: 3}
my_map
%{a: first, b: second, c: third} = %{a: 1, b: 2, c: 3}
first
%{b: second} = my_map
second
my_map.a
map2 = %{"a" => 1, "b" => 2, "c" => 3}
%{"c" => c} = map2
c
map2 = %{map2 | "c" => 4}
my_map = %{my_map | a: 5}

Struct

defmodule User do
  defstruct username: "", age: nil, email: ""
end
user1 = %User{username: "Octallium", age: 14, email: "octobot@sample.com"}
%{username: username} = user1
username
user1 = %{user1 | age: 21}
user1