Types
Atom
:error
{:error, reason} = {:error, "file not found"}
reason
{:ok, msg} = {:ok, "Status 200 OK"}
msg
String
name = "Kantum"
is_binary(name)
msg = "Hello " <> name
"Hello " <> pm_name = msg
pm_name
<> = name
head
Code point with ?
⚠️ I’m not sure to understand this. Get the binary representation of the char
head == ?K
<<"Ka", rest::binary>> = name
rest
<> = name
head
Charlist
chars = ~c"Kantum"
~c"Hello " ++ chars
is_list(chars)
?A
Process
my_pid = self()
my_pid
List
Lists are actually linked list. You cannot dereference with [], you can however use a function like Enum.at(list, index)
Enum. in iex to see all availables function including at/2. The /2
part is called the arity and tells how many argument the function takes.
h Enum.at
in iex for help about the function:
iex(2)> h Enum.at
def at(enumerable, index, default \\ nil)
@spec at(t(), index(), default()) :: element() | default()
Finds the element at the given index (zero-based).
Returns default if index is out of bounds.
A negative index can be passed, which means the enumerable is enumerated once
and the index is counted from the end (for example, -1 finds the last element).
## Examples
iex> Enum.at([2, 4, 6], 0)
2
iex> Enum.at([2, 4, 6], 2)
6
iex> Enum.at([2, 4, 6], 4)
nil
iex> Enum.at([2, 4, 6], 4, :none)
:none
list = ["a", "b", "c"]
list[0]
Enum.at(list, 0)
[first, second, third] = list
second
[_, _, third] = list
third
hd(list)
tl(list)
|
is called cons, it constructs lists, here to have the same behavior as hd() and tl()
[h | t] = list
t
Tuple
{a, b} = {1, 2}
a
{:reply, msg, state} = {:reply, "Bobs found", ["Bobby Lapointe", "Bob dylan", "Bob Ross"]}
state
Keyword List
data = [a: 1, b: 2]
[{:a, 1}] = [a: 1]
data[:b]
Map
my_map = %{a: 1, b: 2, c: 3}
%{a: first, b: second}
my_map.a
If the key is not an atom, we need to the arrow notation =>
. Still don’t know what is this.
map2 = %{"a" => 1, "b" => 2}
%{"b" => b} = map2
b
map2 = %{map2 | "b" => 4}
my_map = %{my_map | b: 12}
Struct
defmodule
and defstruct
is a macro. Struct are very similar to maps.
defmodule User do
defstruct username: "", email: "", age: nil
end
user1 = %User{username: "Kantum", age: 12, email: "42kantum@gmail.com"}
%{username: username} = user1
%{user1 | age: 42}