Monad.Writer

The writer monad keeps track of a calculation and a “log”.

The log can be anything that conforms to the Monoid protocol.

It’s often useful to combine the writer monad with others. For example, you can use a Monad.Maybe as the value of the writer monad. This offers the benefit of having a log of a writer monad and the control flow of a maybe monad.

Source

Summary

bind(writer, fun)

Callback implementation of Monad.Behaviour.bind/2

return(value)

Callback implementation of Monad.Behaviour.return/1

runWriter(writer)

Returns the value and log from a writer monad

writer(value)

Wraps value into a writer monad

writer(value, log)

Wraps value and log into a writer monad

Types

t

Functions

bind(writer, fun)

Specs:

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

Callback implementation of Monad.Behaviour.bind/2.

Unwraps the value from writer and applies it to fun. The log from writer and from the resulting writer monad are combined.

iex> m = writer 4, ["Four"]
iex> n = bind m, (& writer &1 * 2, ["Doubled"])
iex> runWriter n
{8, ["Four", "Doubled"]}
Source
return(value)

Specs:

  • return(term) :: t

Callback implementation of Monad.Behaviour.return/1.

Wraps value into a writer monad.

iex> return 42
%Monad.Writer{value: 42, log: :nil_monoid}
Source
runWriter(writer)

Specs:

Returns the value and log from a writer monad.

iex> w = writer 42, "The answer"
iex> runWriter w
{42, "The answer"}
Source
writer(value)

Specs:

  • writer(term) :: t

Wraps value into a writer monad.

iex> writer 42
%Monad.Writer{value: 42, log: :nil_monoid}
Source
writer(value, log)

Specs:

Wraps value and log into a writer monad.

iex> writer 42, "The answer"
%Monad.Writer{value: 42, log: "The answer"}
Source