typestar

with chains in Elixir

A launch checklist: with walks the happy path of ok tuples and else catches the first miss.

defmodule Launch do
  defp fuel(:full), do: {:ok, 100}
  defp fuel(_tank), do: {:error, :fuel_low}

  defp weather("clear"), do: {:ok, "clear"}
  defp weather(sky), do: {:error, {:sky, sky}}

  # with chains steps that must all match; else handles any miss.
  def go?(tank, sky) do
    with {:ok, pct} <- fuel(tank),
         {:ok, _} <- weather(sky) do
      "launch with #{pct}% fuel"
    else
      {:error, why} -> "scrubbed: #{inspect(why)}"
    end
  end
end

IO.puts(Launch.go?(:full, "clear"))
IO.puts(Launch.go?(:full, "storm"))

How it works

  1. fuel and weather each return {:ok, ...} or {:error, ...}.
  2. with matches each <- step in order; passing them all reaches the do block.
  3. The first failed match falls to else, which reports why the launch scrubbed.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
490
Tokens
151
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 129 seconds.

Type this snippet

Step 2 of 3 in Control flow, step 20 of 27 in Language basics.

← Previous Next →