Monad.Maybe

A monad that represents something or nothing.

The concept of having something vs. nothing is similar to having a value vs. nil.

Source

Summary

bind(maybe, fun)

Callback implementation of Monad.Behaviour.bind/2

none()

Returns a “nothing” state

none?(maybe)

Macro that indicates if the maybe monad contains nothing

pure(value)

An alias for some/1

return(value)

Callback implementation of Monad.Behaviour.return/1

some(value)

Wraps the value into a maybe monad

some?(maybe)

Macro that indicates if the maybe monad contains something

unwrap!(maybe)

Unwraps the value from a maybe monad

Types

t

maybe_type :: :some | :none

The possible types of values that can occur (i.e. something and nothing).

Functions

bind(maybe, fun)

Specs:

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

Callback implementation of Monad.Behaviour.bind/2.

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

For none monads, none is returned without evaluating fun.

iex> m = some 42
iex> n = bind m, (& some &1 * 2)
%Monad.Maybe{type: :some, value: 84}

iex> bind none, (& some &1 * 2)
none
Source
pure(value)

Specs:

  • pure(term) :: t

An alias for some/1.

Source
return(value)

Specs:

  • return(term) :: t

Callback implementation of Monad.Behaviour.return/1.

Wraps the value in a maybe monad.

iex> return 42
%Monad.Maybe{type: :some, value: 42}
Source
some(value)

Specs:

  • some(term) :: t

Wraps the value into a maybe monad.

iex> some 42
%Monad.Maybe{type: :some, value: 42}
Source
unwrap!(maybe)

Specs:

  • unwrap!(t) :: term

Unwraps the value from a maybe monad.

Does not work with none values, since they contain nothing.

iex> m = some 42
iex> unwrap! m
42
Source

Macros

none()

Returns a “nothing” state.

Source
none?(maybe)

Macro that indicates if the maybe monad contains nothing.

This macro may be used in guard clauses.

iex> none? none
true
iex> none? some 42
false
Source
some?(maybe)

Macro that indicates if the maybe monad contains something.

This macro may be used in guard clauses.

iex> some? none
false
iex> some? some 42
true
Source