Flow Control
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 Caeser"}
case post1 do
%{author: "Shivam"} -> "Got a post from Shivam"
%{author: "Anil Kulkarni"} -> "Got a post from Anil Kulkarni"
%{author: author} -> "Got a post from #{author}"
end
post1 = %{post1 | author: "Anil Kulkarni"}
Cond
cond do
post1.author == "Shivam" -> "Editing a post from Shivam"
post1.author == "Anil Kulkarni" -> "Editing a post from Anil Kulkarni"
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