{- | An effect providing access to an immutable (but locally-modifiable) context value.

This effect is similar to the traditional @MonadReader@ typeclass, though it allows the presence of multiple @Reader t@ effects.

Predefined carriers:

* "Control.Carrier.Reader".
* "Control.Monad.Trans.Reader".
* "Control.Monad.Trans.RWS.Lazy"
* "Control.Monad.Trans.RWS.Strict"
* If 'Reader' @r@ is the last effect in a stack, it can be interpreted directly to @(-> r)@ (a function taking an @r@).

@since 0.1.0.0
-}

module Control.Effect.Reader
( -- * Reader effect
  Reader(..)
, ask
, asks
, local
  -- * Re-exports
, Algebra
, Effect
, Has
, run
) where

import Control.Algebra
import Control.Effect.Reader.Internal (Reader(..))

-- | Retrieve the environment value.
--
-- @
-- runReader a ('ask' '>>=' k) = runReader a (k a)
-- @
--
-- @since 0.1.0.0
ask :: Has (Reader r) sig m => m r
ask :: m r
ask = Reader r m r -> m r
forall (eff :: (* -> *) -> * -> *) (sig :: (* -> *) -> * -> *)
       (m :: * -> *) a.
(Member eff sig, Algebra sig m) =>
eff m a -> m a
send ((r -> m r) -> Reader r m r
forall r (m :: * -> *) k. (r -> m k) -> Reader r m k
Ask r -> m r
forall (f :: * -> *) a. Applicative f => a -> f a
pure)

-- | Project a function out of the current environment value.
--
-- @
-- 'asks' f = 'fmap' f 'ask'
-- @
--
-- @since 0.1.0.0
asks :: Has (Reader r) sig m => (r -> a) -> m a
asks :: (r -> a) -> m a
asks f :: r -> a
f = Reader r m a -> m a
forall (eff :: (* -> *) -> * -> *) (sig :: (* -> *) -> * -> *)
       (m :: * -> *) a.
(Member eff sig, Algebra sig m) =>
eff m a -> m a
send ((r -> m a) -> Reader r m a
forall r (m :: * -> *) k. (r -> m k) -> Reader r m k
Ask (a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (a -> m a) -> (r -> a) -> r -> m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. r -> a
f))

-- | Run a computation with an environment value locally modified by the passed function.
--
-- @
-- runReader a ('local' f m) = runReader (f a) m
-- @
--
-- @since 0.1.0.0
local :: Has (Reader r) sig m => (r -> r) -> m a -> m a
local :: (r -> r) -> m a -> m a
local f :: r -> r
f m :: m a
m = Reader r m a -> m a
forall (eff :: (* -> *) -> * -> *) (sig :: (* -> *) -> * -> *)
       (m :: * -> *) a.
(Member eff sig, Algebra sig m) =>
eff m a -> m a
send ((r -> r) -> m a -> (a -> m a) -> Reader r m a
forall r (m :: * -> *) k b.
(r -> r) -> m b -> (b -> m k) -> Reader r m k
Local r -> r
f m a
m a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure)