moonsugar v0.1.0 Moonsugar.Result
The Result module contains functions that help create and interact with the result type.
Link to this section Summary
Functions
Attempts to do something that might throw an error, and converts the out put to a result type
Like map, but chain takes a function that returns a result type This prevents nested results
Helper function to create a error type
converts a variable from a maybe type to a result type
converts a variable that might be nil to a result type
converts a variable from a validation type to a result type
Extracts a value from a result type If the provided argument doesn’t have a value, the default is returned
determines if a value is a result type
maps over a result type
Helper function to create an ok type
Link to this section Functions
Attempts to do something that might throw an error, and converts the out put to a result type
Examples
iex> Result.attempt(“Shoot Elf”)
iex> Result.attempt(raise(“You Died”))
Like map, but chain takes a function that returns a result type This prevents nested results
Examples
iex> Result.map({:ok, 3}, fn(x) -> …> cond do …> x > 0 -> {:ok, x * 3} …> x <= 0 -> {:error, “number less than 1”} …> end …> end) {:ok, {:ok, 9}}
iex> Result.chain({:ok, 3}, fn(x) -> …> cond do …> x > 0 -> {:ok, x * 3} …> x <= 0 -> {:error, “number less than 1”} …> end …> end)
iex> Result.chain({:ok, 0}, fn(x) -> …> cond do …> x > 0 -> {:ok, x * 3} …> x <= 0 -> {:error, “number less than 1”} …> end …> end)
iex> Result.chain({:error, “no number found”}, fn(x) -> …> cond do …> x > 0 -> {:ok, x * 3} …> x <= 0 -> {:error, “number less than 1”} …> end …> end)
Helper function to create a error type
Examples
iex> Result.error(“Goat is floating”)
converts a variable from a maybe type to a result type
Examples
iex> Result.from_maybe({:just, 3}, “Not a number”)
iex> Result.from_maybe(:nothing, “Not a number”)
converts a variable that might be nil to a result type
Examples
iex> Result.from_nilable(“khajiit has wares”, “khajiit does not have wares”)
iex> Result.from_nilable(nil, “khajiit does not have wares”)
converts a variable from a validation type to a result type
Examples
iex> Result.from_validation({:success, “Dragon Slayed”})
iex> Result.from_validation({:fail, [“You Died”, “You ran out of mana”]})
Extracts a value from a result type If the provided argument doesn’t have a value, the default is returned
Examples
iex> Result.getWithDefault({:ok, 3}, 0) 3
iex> Result.getWithDefault({:error, “Game Crashed”}, 0) 0
determines if a value is a result type
Examples
iex> Result.is_result({:ok, 0}) true
iex> Result.is_result({:error, “Not enough ore”}) true
iex> Result.is_result({:just, 3}) false
maps over a result type
Examples
iex> Result.map({:ok, 3}, fn(x) -> x * 2 end)
iex> Result.map({:error, “Dwarves”}, fn(x) -> x * 2 end)
Helper function to create an ok type
Examples
iex> Result.ok(3)