Powered by AppSignal & Oban Pro

制御構造

livebooks/03_Control.livemd

制御構造

if

条件に該当した値が返る

if String.valid?("Hello") do
  "Valid string!"
else
  "Invalid string."
end

該当するものがなければ nil が返る

if String.length("Hello") < 3 do
  "!!!"
end

if の結果で変数を束縛する

res =
  if is_atom(:foo) do
    ":foo is atom"
  else
    "not atom"
  end

unless

if の逆で、該当しない場合に値を返す

a = 1

unless a < 0 do
  "!!!"
end
unless a > 0 do
  "!!!"
end

case

パターンマッチによって分岐する

_ で「上記以外」を表す

case {:ok, "Hello World"} do
  {:ok, result} -> result
  {:error} -> "Uh oh!"
  _ -> "Catch all"
end

該当するケースが存在しない場合はエラーになる

case :even do
  :odd -> "Odd"
end
case :even do
  :odd -> "Odd"
  _ -> "Not Odd"
end

when によってさらに条件を付与できる

case {1, 2, 3} do
  {1, x, 3} when x > 0 ->
    "Will match"

  _ ->
    "Won't match"
end

cond

条件を羅列して分岐する

cond do
  2 + 2 == 5 ->
    "This will not be true"

  2 * 2 == 3 ->
    "Nor this"

  1 + 1 == 2 ->
    "But this will"
end

true で「上記以外」を表す

cond do
  7 + 1 == 0 -> "Incorrect"
  true -> "Catch all"
end

with

条件に使用する変数を束縛する

user = %{first: "Sean", last: "Callan"}
with {:ok, first} <- Map.fetch(user, :first),
     {:ok, last} <- Map.fetch(user, :last),
     do: last <> ", " <> first
with {:ok, middle} <- Map.fetch(user, :middle),
     {:ok, last} <- Map.fetch(user, :last),
     do: last <> ", " <> middle