Monk
Monk is your everyday :ok | :error
monad.
The monk macro allows you to pipe functions that accept a mere value, and
returns wrapped values like {ok:, val}
or {:error, val}
.
If a function returns {:error, reason}
, the subsequent functions in the pipe
will not be called and the result of the whole expression will be the
{:error, _}
tuple.
Some functions don’t return any data, just :ok
. The value :ok
(the single
atom) will be passed along as-is to the next function in the pipe.
Of course, you need to use Monk
to be able to call the macro.
Two syntaxes are supported :
result = monk data |> map |> reduce
monk do
some |> nice |> piping
end
If you except an error from a function, you can catch the error and continue
through the pipe with the ok/1 function. The next function will receive the
{:error, reason}
tuple as it’s first argument. Here, report_error
receives
any value that is returned by do_things
monk bad_data |> ok(do_things) |> report_error
This could be read as the following :
{:ok, d} = bad_data()
{:ok, {:error, e}} = ok(do_things(d))
report_error({:error, e})
Summary
err(reason) | Wraps an error description in a {:error, _} tuple. Values already wrapped are not touched |
monk(pipe_expr) | |
ok(val) | Wraps a value in a {:ok, _} tuple. Values already wrapped are not touched |
unwrap(val) | Unwraps all levels of {:ok, } or {:error, } wrappings |
wrap(val) | Wraps a term in a {:ok, _} tuple or in an error if the value is either nil or the :error atom. Values already wrapped are not touched |
Functions
Specs:
- err(term) :: {:error, term}
Wraps an error description in a {:error, _} tuple. Values already wrapped are not touched.
Specs:
- ok(term) :: {:ok, term}
Wraps a value in a {:ok, _} tuple. Values already wrapped are not touched.
Unwraps all levels of {:ok, } or {:error, } wrappings.
The top wrap defines what is unwrapped. If the top wrap is :ok, the :error wraps will not be removed :
unwrap({:ok,{:ok,{:error,val}}}) -> {:error,val}
Specs:
- wrap(term) :: {:error, term} | {:ok, term}
Wraps a term in a {:ok, _} tuple or in an error if the value is either nil or the :error atom. Values already wrapped are not touched.