typestar

Tuples and :ok pairs in Elixir

The {:ok, value} and {:error, reason} convention, spoken here by a stubborn vault.

# A tuple is a fixed-size bundle; {:ok, value} and {:error, reason}
# are the shapes every Elixir library speaks.
defmodule Vault do
  def open("6-2-8"), do: {:ok, "deed to the tin mine"}
  def open(_guess), do: {:error, :wrong_combination}
end

{:ok, prize} = Vault.open("6-2-8")
IO.puts("inside: #{prize}")

{:error, reason} = Vault.open("1-1-1")
IO.puts("no luck: #{reason}")

How it works

  1. Vault.open returns {:ok, ...} for the right combination and {:error, ...} for the rest.
  2. {:ok, prize} = ... matches the success shape and binds the payload in one line.
  3. The failing call matches {:error, reason}, and the atom prints as plain text.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
374
Tokens
86
Three-star pace
75 tpm

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

Type this snippet

Step 2 of 3 in Lists & tuples, step 8 of 27 in Language basics.

← Previous Next →