ex_optional v0.1.2 ExOptional

ExOptional provides a (minimal) set of functions to work with “Optional” types.

In Elixir, Optional types are really just two-element tuples. Success Optionals look like

{ :ok, value }

while failed Optionals have some other value for the first element. (ExOptional uses :no by default, but largely doesn’t care.)

Currently, failed Optionals will only have a value of nil. In the future, ExOptional may support failed values as well.

Summary

Functions

Test if an Optional is failed

Unwrap a value from a success Optional

Apply an Optional to a function

Apply an Optional to a function, specified by Module, Function, and Args (MFA)

Test if an Optional is successful

Wrap a value as a success Optional

Functions

fail?(opt)

Test if an Optional is failed.

Returns true or false.

Examples

iex> ExOptional.fail?( { :ok, 123 } )
false
from_optional(opt)

Unwrap a value from a success Optional.

Examples

iex> ExOptional.from_optional( { :ok, 123 } )
123

iex> ExOptional.from_optional( { :no, 123 } )
nil
opt_apply(opt, fun, args)

Apply an Optional to a function.

Examples

iex> ExOptional.opt_apply( { :ok, [ 1, 2, 3 ] }, &Enum.map/2, fn x -> x * 2 end )
{ :ok, [ 2, 4, 6 ] }

iex> ExOptional.opt_apply( { :no, nil }, &Enum.map/2, fn x -> x * 2 end )
{ :no, nil }
opt_apply(opt, module, fun_atom, args)

Apply an Optional to a function, specified by Module, Function, and Args (MFA).

Examples

iex> ExOptional.opt_apply( { :ok, [ 1, 2, 3 ] }, Enum, :map, fn x -> x * 2 end )
{ :ok, [ 2, 4, 6 ] }

iex> ExOptional.opt_apply( { :no, nil }, Enum, :map, fn x -> x * 2 end )
{ :no, nil }
success?(opt)

Test if an Optional is successful.

Returns true or false.

Examples

iex> ExOptional.success?( { :ok, 123 } )
true
to_optional(value)

Wrap a value as a success Optional.

Returns { :ok, value }.

Examples

iex> ExOptional.to_optional( 123 )
{ :ok, 123 }