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

Flow Control

flow_control.livemd

Flow Control

Case

list = [1, 2, 3]
case Enum.at(list, 3) 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 01", author: "Jules César"}
case post1 do
  %{author: "Kantum"} -> "Kantum doesn't know how to write"
  _ -> "Got a post from #{post1.author}"
end
post1 = %{post1 | author: "Kantum"}
case post1 do
  %{author: "Kantum"} -> "Kantum doesn't know how to write"
  _ -> "Got a post from #{post1.author}"
end

Cond

cond do
  post1.author == "Kantum" -> "Stop"
  post1.author == "Jules César" -> "Stop"
  post1.author == "Kantum" -> "Stop"
  true -> "This is a catchall"
end
cond do
  hd(list) == 1 -> "Got a 1"
  true -> "Head is #{hd(list)}"
end

If/Else

if true do
  "This will work"
else
  "This is no work"
end