View Source Funx.Monad.Reader (funx v0.2.3)

The Funx.Monad.Reader module represents the Reader monad, which allows computations to access shared, read-only environment values.

This module defines core Reader functions:

  • pure/1 – Lifts a value into the Reader context.
  • run/2 – Executes the Reader with a given environment.
  • asks/1 – Extracts and transforms a value from the environment.
  • ask/0 – Extracts the full environment.
  • tap/2 – Executes a side-effect function on the computed value, returning the original Reader unchanged.

This module implements the following protocol:

  • Funx.Monad: Implements bind/2, map/2, and ap/2 for monadic composition.

Note: The Reader monad does not implement Eq or Ord, since Readers are lazy— they do not actually contain a value until they are run. We only can compare the results of a Reader, not the Reader itself.

Summary

Functions

Extracts the value contained in the environment, making it available within the Reader context.

Extracts and transforms the value contained in the environment, making it available within the Reader context.

Lifts a value into the Reader context.

Runs the Reader with the provided environment, returning the computed value.

Executes a side-effect function on the computed value and returns the original Reader unchanged.

Types

@type t(env, value) :: %Funx.Monad.Reader{run: (env -> value)}

Functions

@spec ask() :: t(Env, Env)

Extracts the value contained in the environment, making it available within the Reader context.

Examples

iex> reader = Funx.Monad.Reader.ask()
iex> Funx.Monad.Reader.run(reader, %{foo: "bar"})
%{foo: "bar"}
@spec asks(func :: (Env -> A)) :: t(Env, A)

Extracts and transforms the value contained in the environment, making it available within the Reader context.

Examples

iex> reader = Funx.Monad.Reader.asks(fn env -> Map.get(env, :foo) end)
iex> Funx.Monad.Reader.run(reader, %{foo: "bar"})
"bar"
@spec pure(value :: A) :: t(any(), A)

Lifts a value into the Reader context.

Examples

iex> reader = Funx.Monad.Reader.pure(42)
iex> Funx.Monad.Reader.run(reader, %{})
42
@spec run(t(Env, A), Env) :: A

Runs the Reader with the provided environment, returning the computed value.

Examples

iex> reader = Funx.Monad.Reader.pure(42)
iex> Funx.Monad.Reader.run(reader, %{})
42
@spec tap(t(Env, A), (A -> any())) :: t(Env, A)

Executes a side-effect function on the computed value and returns the original Reader unchanged.

Useful for debugging, logging, or performing side effects in the middle of a Reader pipeline without changing the computed value. The side effect executes when the Reader is run.

Examples

iex> reader = Funx.Monad.Reader.pure(5) |> Funx.Monad.Reader.tap(fn x -> x * 2 end)
iex> Funx.Monad.Reader.run(reader, %{})
5