View Source Funx.Monad.Reader (funx v0.1.0)
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.
This module implements the following protocol:
Funx.Monad
: Implementsbind/2
,map/2
, andap/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.
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"
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