Monad.Result

A monad that represents success and failure conditions.

In a series of bind operations, if any function returns an error monad, the following binds are skipped. This allows for easy flow control for both success and error cases.

Source

Summary

bind(result, fun)

Callback implementation of Monad.Behaviour.bind/2

error(error)

Wraps a value in an error monad

error?(result)

Returns true if the given monad contains an error state

from_tuple(arg1)

Converts a standard success/failure tuple to a Monad.Result

return(value)

Callback implementation of Monad.Behaviour.return/1

success(value)

Wraps a value in a success monad

success?(result)

Returns true if the given monad contains a success state

unwrap!(result)

Unwraps the value from a success monad

Types

t

result_type :: :ok | :error

The possible types of results that can occur (i.e. success and failure).

result_tuple :: {result_type, term}

The standard tuple format for representing success and error states.

These tuples are easily converted to a Monad.Result.

Functions

bind(result, fun)

Specs:

  • bind(t, (term -> t)) :: t

Callback implementation of Monad.Behaviour.bind/2.

If the monad contains a success state, then the value is unwrapped and applied to fun.

For monads containing an error state, the error is returned as is.

iex> s = success 42
iex> r = bind s, (& success &1 * 2)
iex> r.value
84
iex> r.error
nil

iex> s = success 42
iex> r = bind s, fn _ -> error "Failed" end
iex> r.value
nil
iex> r.error
"Failed"
Source
error(error)

Specs:

  • error(term) :: t

Wraps a value in an error monad.

iex> e = error "Failed"
iex> e.value
nil
iex> e.error
"Failed"
Source
error?(result)

Specs:

  • error?(t) :: boolean

Returns true if the given monad contains an error state.

iex> e = error "Failed"
iex> error? e
true
Source
from_tuple(arg1)

Specs:

Converts a standard success/failure tuple to a Monad.Result.

iex> s = from_tuple {:ok, 42}
iex> s.value
42
iex> s.error
nil

iex> e = from_tuple {:error, "Failed"}
iex> e.value
nil
iex> e.error
"Failed"
Source
return(value)

Specs:

  • return(term) :: t

Callback implementation of Monad.Behaviour.return/1.

Wraps a value in a success monad.

iex> s = return 42
iex> s.value
42
iex> s.error
nil
Source
success(value)

Specs:

  • success(term) :: t

Wraps a value in a success monad.

iex> s = success 42
iex> s.value
42
iex> s.error
nil
Source
success?(result)

Specs:

  • success?(t) :: boolean

Returns true if the given monad contains a success state.

iex> s = success 42
iex> success? s
true
Source
unwrap!(result)

Specs:

  • unwrap!(t) :: term

Unwraps the value from a success monad.

Does not work with error monads.

iex> s = success 42
iex> unwrap! s
42
Source