moonsugar v0.1.0 Moonsugar.Maybe
The Maybe module contains functions that help create and interact with the maybe type. The Maybe type used in this library is represented as either a Just type or a Nothing type.
Link to this section Summary
Functions
Like map, but chain takes a function that returns a maybe type This prevents nested maybes
converts a variable that might be nil to a maybe type
converts a variable from a result type to a maybe type
converts a variable from a validation type to a maybe type
Extracts a value from a maybe type If the provided argument doesn’t have a value, the default is returned
determines if a value is a maybe type
Helper function to create a just type
maps over a maybe type
Helper function to create a nothing type
Link to this section Functions
Like map, but chain takes a function that returns a maybe type This prevents nested maybes
Examples
iex> Maybe.map({:just, 3}, fn(x) -> …> cond do …> x > 0 -> {:just, x * 3} …> x <= 0 -> :nothing …> end …> end) {:just, {:just, 9}}
iex> Maybe.chain({:just, 3}, fn(x) -> …> cond do …> x > 0 -> {:just, x * 3} …> x <= 0 -> :nothing …> end …> end)
iex> Maybe.chain({:just, 0}, fn(x) -> …> cond do …> x > 0 -> {:just, x * 3} …> x <= 0 -> :nothing …> end …> end) :nothing
converts a variable that might be nil to a maybe type
Examples
iex> Maybe.from_nilable(“khajiit has wares”)
iex> Maybe.from_nilable(nil) :nothing
converts a variable from a result type to a maybe type
Examples
iex> Maybe.from_result({:ok, 3})
iex> Maybe.from_result({:error, “I took an arrow to the knee”}) :nothing
converts a variable from a validation type to a maybe type
Examples
iex> Maybe.from_validation({:success, “Dragon Slayed”})
iex> Maybe.from_result({:fail, [“You Died”]}) :nothing
Extracts a value from a maybe type If the provided argument doesn’t have a value, the default is returned
Examples
iex> Maybe.getWithDefault({:just, 3}, 0) 3
iex> Maybe.getWithDefault(:nothing, 0) 0
determines if a value is a maybe type
Examples
iex> Maybe.is_maybe({:just, 0}) true
iex> Maybe.is_maybe(:nothing) true
iex> Maybe.is_maybe({:ok, 3}) false
Helper function to create a just type
Examples
iex> Maybe.just(3)
maps over a maybe type
Examples
iex> Maybe.map({:just, 3}, fn(x) -> x * 2 end)
iex> Maybe.map(:nothing, fn(x) -> x * 2 end) :nothing
Helper function to create a nothing type
Examples
iex> Maybe.nothing() :nothing