Shawn Livebook freecode camp
Section
Atom
:error
{:error, reason} = {:error, "file not found"}
{:ok, msg} = {:ok, "status 200 ok"}
msg
name = "Shawn"
msg = "Hello " <> name
<<head, rest::binary>> = name
head
?s
?h
?a
?w
?n
head == ?S
<<"S", rest::binary>> = name
rest
chars = "Mumbo"
'Hello ' ++ chars
my_pid = self()
my_pid
Linked lists
list = ["a", "b", "c"]
Enum.at(list, 0)
[first, second, third] = list
second
[.., .., third]
hd(list)
tl(list)
[h | t] = list
h
Tuple
{a, b, c} = {1, 2, 3}
a
{:reply, msg, state} = {:reply, "Spirit of Ecstacy", ["Shawn", "Albert", "Owino"]}
msg
Keyword List
data = [a: 1, b: 2]
[{:a, 1}] = [a: 1]
data[:a]
Maps
my_map = %{a: 1, b: 2, c: 3}
my_map
%{a: first, b: second, c: third} = my_map
first
%{c: third} = my_map
third
my_map.a
map2 = %{"s" => 1, "h" => 2, "a" => 3, "w" => 4, "n" => 5}
%{"w" => w} = map2
w
map2 = %{map2 | "a" => 10}
my_map = %{my_map | c: 7}
Struct
The keyword list used with defstruct defines what fields the struct will have along with their default values.
Structs take the name of the module they’re defined in. In the example above, we defined a struct named User.
We can now create User structs by using a syntax similar to the one used to create maps:
defmodule User do
defstruct username: "", email: "", age: nil
end
user1 = %User{username: "Shawn", age: 26, email: "MUmbo@shawn.owino"}
%{username: username} = user1
username
user1 = %{user1 | age: 21}
Flow Control
case
list = [1, 2, 3]
case Enum.at(list, 2) do
1 -> "This will not print"
3 -> "Found your match"
_ -> "catch hands"
end
defmodule Post do
defstruct(
id: nil,
title: "",
description: "",
author: ""
)
end
post1 = %Post{id: 1, title: "Title No 1", author: "Julius Caeser"}
case post1 do
%{author: "Shawn"} -> "Got a post from Shawn"
%{author: "Anil Mumbo"} -> "Got a post from Anil Mumbo"
%{author: author} -> "Got a post from #{author}"
end
post1 = %{post1 | author: "Anil Mumbo"}
Cond
cond do
post1.author == "Shawn" -> "Editing a post from Shawn"
post1.author == "Anil Mumbo" -> "Editing a post from Anil Mumbo"
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