Skip to main content

Reader

Environment variables, like impure I/O operations, have the capacity to break function purity. The Reader monad is a solution to interacting with an external environment - that inclusive of data with wide-reaching configuration value. The monad localizes state changes dependent on the said data to ensure that functions are kept pure.

reader#

reader(operation)

reader :: (r -> a) -> m a

Puts a value in a Reader environment - calls the Reader monad constructor and initializes a value of type Reader.

Since:

  • bingo-functional - v1.11.0
  • bingo-functional-js - v0.1.0

Argument(s):

  • operation - Operation to put in the Reader environment
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Monads\Reader\reader;
$hello = reader(f\partial(f\concat, ' ', 'Hello,'));

runReader#

runReader(reader, value)

runReader :: Reader r a -> r -> a

Applies an arbitrary value to a Reader and extracts a value from it.

Since:

  • bingo-functional - v1.11.0
  • bingo-functional-js - v0.1.0

Argument(s):

  • reader - Instance of Reader monad
  • value - Arbitrary value applied to Reader monad
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Monads\Reader\{  reader,  runReader};
$hello = reader(f\partial(f\concat, ' ', 'Hello,'));
runReader($hello, 'Mike');

mapReader#

mapReader(function, reader)

mapReader :: (a -> b) -> Reader r a -> a -> Reader r b

Applies a function to value in a Reader environment.

Since:

  • bingo-functional - v1.11.0
  • bingo-functional-js - v0.1.0

Argument(s):

  • function - An arbitrary function
  • reader - A Reader monad instance
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Monads\Reader\{  reader,  mapReader,  runReader};
$hello  = reader(f\partial(f\concat, ' ', 'Hello,'));
$res    = mapReader('strtoupper', $hello);
runReader($res, 'Mike');

withReader#

withReader(function, reader)

withReader :: (r -> r') -> Reader r a -> Reader r' a

Executes a computation in a modified Reader environment.

Since:

  • bingo-functional - v1.11.0
  • bingo-functional-js - v0.1.0

Argument(s):

  • function - An arbitrary function
  • reader - A Reader monad instance
use Chemem\Bingo\Functional as f;use function Chemem\Bingo\Functional\Functors\Monads\Reader\{  reader,  withReader,  runReader};
$hello  = reader(f\partial(f\concat, ' ', 'Hello,'));
$ask    = withReader(  fn (string $greet) => reader(fn (string $name) => (    f\concat('', $greet, '.', $name === 'world' ? '' : ' How are you?')  )),  $hello);
runReader($ask, 'Mike');

ask#

ask()

ask :: m r

Retrieves the Reader monad environment.

Since:

  • bingo-functional - v1.11.0
  • bingo-functional-js - v0.1.0

Argument(s):

None

use function Chemem\Bingo\Functional\Functors\Monads\Reader\ask;
$result = ask();