Data Types
Atom
:error
{:error, reason} = {:error, "file not found"}
reason
{:ok, msg} = {:ok, "status 200 ok"}
msg
Strings
name = "Octallium"
name
is_binary(name)
msg = "Hello " <> name
msg
"Hello " <> name = msg
name
<> = name
head
head == ?O
<<"O", rest::binary>> = name
rest
<<"Oc", rest::binary>> = name
rest
<> = name
head
Charlist
chars = 'Octallium'
Processes
my_pid = self()
my_pid
Lists
# Lists in elixir are singly linked lists.
list = ["a", "b", "c"]
# we have linked lists in elixir because they are recursive in nature.
# we can work with them with recusrsive functions or some modules.
Enum.at(list, 0)
[first, second, third] = list
[_, _, third] = ["a", "b", "c"]
third
[ h | t ] = list
h
Tuple
{ a,b } = { 1,2 }
a
{:reply, msg, state} = {:reply, "Octallium found!", ["Octallium", "Louis", "Chiko"]}
state
Keyword List
data = [a: 1, b: 2]
[{:a, a}] = [a: 1]
Maps
my_map = %{a: 1, b: 2, c: 3}
my_map
%{a: first, b: second, c: third} = my_map
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 | c: 4}
Struct
defmodule User do
defstruct username: "", email: "", age: nil
end
user1 = %User{username: "Octallium", age: 14, email: "octobot@sample.com"}
%{username: username} = user1
username
user1 = %{user1 | age: 21}
Control Flow
Case
list = [1, 2, 3]
case Enum.at(list, 2) do
1 -> "This won't print"
3 -> "3 is a match!"
_ -> "Catch all"
end
defmodule Post do
defstruct(
id: nil,
title: "",
description: "",
author: ""
)
end
post1 = %Post{id: 1, title: "Title No 1", author: "Julius Ceaser"}
case post1 do
%{author: "Ocatllium"} -> "Got a post from Ocatllium"
%{author: "Arnold"} -> "Got a post from Arnold"
_ -> "Got a post from #{post1.author}"
end
post1 = %{post1 | author: "Anil Kulkarni"}
case post1 do
%{author: "Ocatllium"} -> "Got a post from Ocatllium"
%{author: "Arnold"} -> "Got a post from Arnold"
_ -> "Got a post from #{post1.author}"
end
Cond
cond do
post1.author == "Ocatllium" -> "Editing a post from Octallium"
post1.author == "Arnold" -> "Editing a post from Arnold"
true -> "This is a catch all"
end
cond do
hd(list) == 1 -> "Got a 1"
true -> "Head is #{hd(list)}"
end
If/Else
if true do
"This will work"
else
"Else this will work"
end