Elixir Result Tuples
A result tuple is a tuple that reports whether a step worked. It starts with :ok for success or :error for failure.
Parse functions return a tuple
Integer.parse reads a whole number from text. Float.parse reads a decimal number from text.
IO.inspect(Integer.parse("42"))
IO.inspect(Integer.parse("42px"))
IO.inspect(Float.parse("3.5"))Unreadable text returns :error
Text with no leading number cannot be parsed. Both parse functions answer with the atom :error.
IO.inspect(Integer.parse("abc"))
IO.inspect(Float.parse("abc"))A function can return result tuples
This small module follows the same convention. It wraps a parsed number in :ok and reports bad text with :error.
defmodule Parser do
def parse_number(text) do
case Integer.parse(text) do
{number, ""} -> {:ok, number}
_ -> {:error, :not_a_number}
end
end
end
IO.inspect(Parser.parse_number("25"))
IO.inspect(Parser.parse_number("ten"))Example
defmodule Parser do
def parse_number(text) do
case Integer.parse(text) do
{number, ""} -> {:ok, number}
_ -> {:error, :not_a_number}
end
end
end
case Parser.parse_number("25") do
{:ok, number} -> IO.puts("Accepted: #{number}")
{:error, reason} -> IO.puts("Rejected: #{reason}")
end
case Parser.parse_number("ten") do
{:ok, number} -> IO.puts("Accepted: #{number}")
{:error, reason} -> IO.puts("Rejected: #{reason}")
endKey points
- Result tuple: a two-element tuple whose first element is :ok or :error.
- Success: an :ok tuple carries the produced value as its second element.
- Failure: an :error tuple carries a reason as its second element.
- Integer.parse: it returns {number, leftover} for text it can read and :error for text it cannot.
- Case: a case statement matches the tuple and runs the branch for its shape.
- Convention: your own functions can return {:ok, value} or {:error, reason} the same way.
In this example, Parser.parse_number first returns {:ok, 25}, so the first case prints the number. The second call returns {:error, :not_a_number}, so the matching branch prints the reason without its colon.
Note
:error on its own, with no tuple around it, is the failure answer from Integer.parse.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does Integer.parse("abc") return?