-- | Support for accumulation of values in a thread local list.
--
-- @since 2.7.0.0
module Effectful.Output.Static.Local.List
  ( -- * Effect
    Output

    -- ** Handlers
  , runOutput

    -- ** Operations
  , output
  ) where

import Data.Kind

import Effectful
import Effectful.Dispatch.Static

-- | Provide access to accumulation of values of type @o@ in a thread local
-- list.
data Output (o :: Type) :: Effect

type instance DispatchOf (Output o) = Static NoSideEffects
newtype instance StaticRep (Output o) = Output [o]

-- | Run the 'Output' effect and return the final value along with the
-- accumulated list.
runOutput :: HasCallStack => Eff (Output o : es) a -> Eff es (a, [o])
runOutput :: forall o (es :: [(Type -> Type) -> Type -> Type]) a.
HasCallStack =>
Eff (Output o : es) a -> Eff es (a, [o])
runOutput Eff (Output o : es) a
action = do
  (a
a, Output [o]
acc) <- StaticRep (Output o)
-> Eff (Output o : es) a -> Eff es (a, StaticRep (Output o))
forall (e :: (Type -> Type) -> Type -> Type)
       (sideEffects :: SideEffects)
       (es :: [(Type -> Type) -> Type -> Type]) a.
(HasCallStack, DispatchOf e ~ 'Static sideEffects,
 MaybeIOE sideEffects es) =>
StaticRep e -> Eff (e : es) a -> Eff es (a, StaticRep e)
runStaticRep ([o] -> StaticRep (Output o)
forall o. [o] -> StaticRep (Output o)
Output []) Eff (Output o : es) a
action
  (a, [o]) -> Eff es (a, [o])
forall a. a -> Eff es a
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (a
a, [o] -> [o]
forall a. [a] -> [a]
reverse [o]
acc)

-- | Append the value to the end of the list.
output
  :: (HasCallStack, Output o :> es)
  => o -- ^ The value.
  -> Eff es ()
output :: forall o (es :: [(Type -> Type) -> Type -> Type]).
(HasCallStack, Output o :> es) =>
o -> Eff es ()
output !o
o = (StaticRep (Output o) -> ((), StaticRep (Output o))) -> Eff es ()
forall (e :: (Type -> Type) -> Type -> Type)
       (sideEffects :: SideEffects)
       (es :: [(Type -> Type) -> Type -> Type]) a.
(HasCallStack, DispatchOf e ~ 'Static sideEffects, e :> es) =>
(StaticRep e -> (a, StaticRep e)) -> Eff es a
stateStaticRep ((StaticRep (Output o) -> ((), StaticRep (Output o))) -> Eff es ())
-> (StaticRep (Output o) -> ((), StaticRep (Output o)))
-> Eff es ()
forall a b. (a -> b) -> a -> b
$ \(Output [o]
acc) -> ((), [o] -> StaticRep (Output o)
forall o. [o] -> StaticRep (Output o)
Output (o
o o -> [o] -> [o]
forall a. a -> [a] -> [a]
: [o]
acc))