moonsugar v0.1.2 Moonsugar.Maybe

The Maybe module contains functions that help create and interact with the maybe type. The Maybe type is represented as either {:just, value} or :nothing.

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 tuple

Maps over a maybe type

Helper function to create a nothing value

Link to this section Functions

Link to this function chain(maybe, fun)

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)
{:just, 9}

iex> Maybe.chain({:just, 0}, fn(x) ->
...>   cond do
...>     x > 0 -> {:just, x * 3}
...>     x <= 0 -> :nothing
...>   end
...> end)
:nothing
Link to this function from_nilable(val)

Converts a variable that might be nil to a maybe type.

Examples

iex> Maybe.from_nilable("khajiit has wares")
{:just, "khajiit has wares"}

iex> Maybe.from_nilable(nil)
:nothing
Link to this function from_result(result)

Converts a variable from a result type to a maybe type.

Examples

iex> Maybe.from_result({:ok, 3})
{:just, 3}

iex> Maybe.from_result({:error, "I took an arrow to the knee"})
:nothing
Link to this function from_validation(result)

Converts a variable from a validation type to a maybe type.

Examples

iex> Maybe.from_validation({:success, "Dragon Slayed"})
{:just, "Dragon Slayed"}

iex> Maybe.from_result({:fail, ["You Died"]})
:nothing
Link to this function get_with_default(maybe, default)

Extracts a value from a maybe type. If the provided argument doesn’t have a value, the default is returned.

Examples

iex> Maybe.get_with_default({:just, 3}, 0)
3

iex> Maybe.get_with_default(:nothing, 0)
0
Link to this function is_maybe(maybe)

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 tuple.

Examples

iex> Maybe.just(3)
{:just, 3}
Link to this function map(maybe, fun)

Maps over a maybe type.

Examples

iex> Maybe.map({:just, 3}, fn(x) -> x * 2 end)
{:just, 6}

iex> Maybe.map(:nothing, fn(x) -> x * 2 end)
:nothing

Helper function to create a nothing value

Examples

iex> Maybe.nothing()
:nothing