HORIZON HASKELLDocslts/ghc-9.14.x45dd5372026-10-11Search names, modules, packages, or :: a typeCtrl K

GHC 9.14.1 · lts/ghc-9.14.x · 45dd537 · 2026-10-11

Moduleeffectful-core-2.7.1.2GHC2021

Effectful

  • 7 types
  • 4 classes
  • 10 values

Introduction

0 declarations

Haskell is one of the few programming languages that distinguishes between pure functions and functions that might perform side effects. For example, a function

f :: Int -> String

can't perform side effects at all, but a function

f :: Int -> IO String

can perform any side effect. This "all or nothing" approach isn't very satisfactory though, because the vast majority of time we would like to signify that a function can perform some side effects, e.g. only be able to log messages.

This library provides support for expressing exactly that with its Eff monad:

f :: Log :> es => Int -> Eff es String

It implements support for extensible effects with both dynamic and static dispatch. For more information about each type consult the documentation in Effectful.Dispatch.Dynamic and Effectful.Dispatch.Static (when in doubt, start with dynamic dispatch).

The library provides:

  • The Eff monad that tracks effects at the type level. This is going to be the main monad of your application.

  • A set of predefined, basic effects such as Error, Reader, State and Writer.

  • Utilities for defining new effects and interpreting them, possibly in terms of already existing ones (see introduction of the Effectful.Dispatch.Dynamic module for more information).

While basic effects can be used out of the box, in general it's recommended to create your own that serve a more specific purpose.

Integration with existing libraries

Integration with most of existing libraries and frameworks can be done quite easily. The main difference in how that looks like depends on the way a library operates in a monadic context.

There are three main groups a library might fall into. It either operates:

1) In a monad of your application transformed by a library specific monad transformer.

2) In its own, concrete monad, which is usually IO or a couple of monad transformers on top of IO.

3) In a polymorphic monad, which is constrained by a type class that implements core operations of a library.

Each case needs a slightly different approach to integrate with the Eff monad.

Transformed monads

These are libraries that provide a custom transformer for the main monad of your application and their operations make use of it for their operations. Examples include InputT from the haskeline package or ConduitT from the conduit package.

These libraries can trivially be used with the Eff monad since it provides typical instances that these libraries require the underlying monad to have, such as MonadMask or MonadUnliftIO.

In case the Eff monad doesn't provide a specific instance out of the box, it can be supplied via an effect. As an example see how the instance of MonadResource for Eff is implemented in the resourcet-effectful package.

Concrete monads

IO

If a library operates in IO, there are a couple of ways to integrate it.

The easiest way is to use its functions selectively in the Eff monad with the help of liftIO or withEffToIO. However, this is not particularly robust, since it vastly broadens the scope in which the IOE effect is needed (not to mention that explicit lifting is annoying).

A somewhat better approach is to create a dummy static effect with lightweight wrappers of the library functions. As an example have a look at the Effectful.Concurrent.Async module from the effectful package that wraps the API of the async package. Unfortunately, this requires the amount of work proportional to the size of the library and might not be the best option, especially if you only need to make use of a tiny portion of the API.

Even better (though sometimes hard to do in practice) way is to consider, what do you need the library for and then create a custom effect with high level operations that the library in question will help us implement. The advantage of this approach is that we're hiding implementation details from the so-called "business logic" of our application and make it possible to easily swap them in different environments or during future refactoring.

Other

Some libraries operate in a transformer stack over IO or have its own concrete monad that's a newtype over IO, e.g. Handler from the servant-server package.

In such case it's best to mirror the monad in question by the Eff monad with appropriate effects (as most popular monad transformers have subtle issues), use it as soon as possible, then at the end feed the final state to the monad of the library so it proceeds as if nothing unusual happened.

As an example, consider the following monad:

Example2 expressions
import Control.Monad.State qualified as Timport Control.Monad.Except qualified as T
Example2 expressions
data HandlerStatedata HandlerError
Example1 expression
:{  newtype Handler a = Handler (T.ExceptT HandlerError (T.StateT HandlerState IO) a)    deriving ( Applicative, Functor, Monad, MonadIO             , T.MonadState HandlerState, T.MonadError HandlerError             ):}

This is how you can execute Eff actions in the Handler monad:

Example2 expressions
import Effectful.Error.Staticimport Effectful.State.Static.Local
Example1 expression
:{  effToHandler :: Eff [Error HandlerError, State HandlerState, IOE] a -> Handler a  effToHandler m = do    -- Retrieve the current state of the Handler.    s <- T.get    -- Run the Eff monad with effects mirroring the capabilities of @Handler@.    (er, s') <- liftIO . runEff . runState s . runErrorNoCallStack @HandlerError $ m    -- Update the state of the Handler and throw an error if appropriate.    T.put s'    either T.throwError pure er:}

Polymorphic monads

Libraries working in a polymorphic monad use mtl style effects. Details about their integration with the Eff monad require familiarity with dynamically dispatched effects and thus are available in the Effectful.Dispatch.Dynamic#integration module.

The Eff monad

1 declaration
newtypenewtype Eff (es :: [Effect]) a
#

The Eff monad provides the implementation of a computation that performs an arbitrary set of effects. In Eff es a, es is a type-level list that contains all the effects that the computation may perform. For example, a computation that produces an Integer by consuming a String from the global environment and acting upon a single mutable value of type Bool would have the following type:

(Reader String :> es, State Bool :> es) => Eff es Integer

Abstracting over the list of effects with (:>):

  • Allows the computation to be used in functions that may perform other effects.

  • Allows the effects to be handled in any order.

Instances23MonadError, MonadReader, MonadState, MonadWriter, MonadBase, MonadBaseControl, …
  • (Show e, Error e :> es, MonadError e (Eff es)) => MonadError e (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect.Dynamic · orphan

    Instance included for compatibility with existing code.

  • (Reader r :> es, MonadReader r (Eff es)) => MonadReader r (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect.Dynamic · orphan

    Instance included for compatibility with existing code.

  • (State s :> es, MonadState s (Eff es)) => MonadState s (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect.Dynamic · orphan

    Instance included for compatibility with existing code.

  • (Monoid w, Writer w :> es, MonadWriter w (Eff es)) => MonadWriter w (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect.Dynamic · orphan

    Instance included for compatibility with existing code.

    Warning: pass is not implemented due to ambiguous semantics in presence of runtime exceptions, so calling it (also indirectly via censor, which is defined in terms of pass) results in a runtime error.

  • IOE :> es => MonadBase IO (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Instance included for compatibility with existing code.

    Usage of liftIO is preferrable as it's a standard.

  • IOE :> es => MonadBaseControl IO (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Instance included for compatibility with existing code.

    Usage of withEffToIO is preferrable as it allows specifying the UnliftStrategy on a case-by-case basis and has better error reporting.

    Note: the unlifting strategy for liftBaseWith is taken from the IOE context (see unliftStrategy).

  • Monad (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • Functor (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • MonadFix (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • Fail :> es => MonadFail (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • Applicative (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • NonDet :> es => Alternative (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • NonDet :> es => MonadPlus (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • IOE :> es => MonadIO (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • MonadCatch (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Available without any effect requirements.

    This is the one instance of the three that would arguably benefit from requiring IOE (or a more specialized effect), as catching imprecise exceptions makes it possible to write non-deterministic pure functions with runPureEff. Unfortunately it can't, because MonadCatch is a superclass of MonadMask, which needs to be available unconditionally (see the note there).

    For the full discussion see issue #76.

  • MonadMask (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Available without any effect requirements.

    This makes it possible to use cleanup functions such as bracket or finally anywhere, e.g. to restore a state on error:

    transactionally :: forall s es a. State s :> es => Eff es a -> Eff es a
    transactionally = bracketOnError (get @s) (put @s) . const
    

    Requiring IOE would make functions like the above impossible to write and force IOE to show up in application code that otherwise only needs more restricted effects, which would be a significant usability regression. On the other hand, requiring a more specialized effect would be annoying, since functions making use of MonadMask are ubiquitous.

  • MonadThrow (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Available without any effect requirements.

    Gating it behind an effect (such as IOE or a more specialized effect) would accomplish nothing, since any Haskell expression is free to throw an exception with throw at any point.

  • Prim :> es => PrimMonad (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • IOE :> es => MonadUnliftIO (Eff es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

    Instance included for compatibility with existing code.

    Usage of withEffToIO is preferrable as it allows specifying the UnliftStrategy on a case-by-case basis and has better error reporting.

    Note: the unlifting strategy for withRunInIO is taken from the IOE context (see unliftStrategy).

  • Semigroup a => Semigroup (Eff es a)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • Monoid a => Monoid (Eff es a)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • type PrimState (Eff es) = PrimStateEffDefined in effectful-core-2.7.1.2 · Effectful.Internal.Monad
  • type StM (Eff es) a = aDefined in effectful-core-2.7.1.2 · Effectful.Internal.Monad

Effect constraints

familytype family DispatchOf (e :: Effect) :: Dispatch
#

Dispatch types of effects.

Instances28DispatchOf, …
classclass (:>) (e :: Effect) (es :: [Effect]) where
#

A constraint that requires that a particular effect e is a member of the type-level list es. This is used to parameterize an Eff computation over an arbitrary list of effects, so long as e is somewhere in the list.

For example, a computation that only needs access to a mutable value of type Integer would have the following type:

State Integer :> es => Eff es ()
Instances3:>
  • TypeError (('Text "There is no handler for '" ':<>: 'ShowType e) ':<>: 'Text "' in the context") => e :> '[]Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect
  • e :> (e ': es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect
  • e :> es => e :> (x ': es)Defined in effectful-core-2.7.1.2 · Effectful.Internal.Effect
familytype family (:>>) (xs :: [Effect]) (es :: [Effect]) :: Constraint where
#

Deprecated. Usage of (:>>) slows down GHC too much. See https://github.com/haskell-effectful/effectful/issues/52#issuecomment-1269155485 for more information.

Convenience operator for expressing that a function uses multiple effects in a more concise way than enumerating them all with (:>).

[E1, E2, ..., En] :>> es ≡ (E1 :> es, E2 :> es, ..., En :> es)

Equations

  • (:>>) '[] es = ()
  • (:>>) (x ': xs) es = (x :> es, xs :>> es)

Running the Eff monad

0 declarations

Pure computations

valuerunPureEff :: HasCallStack => Eff '[] a -> a
#

Run a pure Eff computation.

For running computations with side effects see runEff.

Note: the computation runs in a separate thread as a workaround for #380.

Computations with side effects

datadata IOE (a :: Type -> Type) b
#

Run arbitrary IO computations via MonadIO or MonadUnliftIO.

Note: it is not recommended to use this effect in application code as it is too liberal. Ideally, this is only used in handlers of more fine-grained effects.

Instances2DispatchOf, StaticRep

Unlifting

datadata UnliftStrategy
#

The strategy to use when unlifting Eff computations via withEffToIO or the localUnlift family.

Constructors

  • SeqUnlift

    The sequential strategy is the fastest and a default setting for IOE. Any attempt of calling the unlifting function in threads distinct from its creator will result in a runtime error.

  • SeqForkUnlift

    Like SeqUnlift, but all unlifted actions will be executed in a cloned environment.

    The main consequence is that thread local state is forked at the point of creation of the unlifting function and its modifications in unlifted actions will not affect the main thread of execution (and vice versa):

    Example3 expressions
    import Effectfulimport Effectful.State.Dynamic:{ action :: (IOE :> es, State Int :> es) => Eff es () action = do   modify @Int (+1)   withEffToIO SeqForkUnlift $ \unlift -> unlift $ modify @Int (+2)   modify @Int (+4):}
    Example1 expression
    runEff . execStateLocal @Int 0 $ action5
    Example1 expression
    runEff . execStateShared @Int 0 $ action7

    Because of this it's possible to safely use the unlifting function outside of the scope of effects it captures, e.g. by creating an IO action that executes effectful operations and running it later:

    Example1 expression
    :{  delayed :: UnliftStrategy -> IO (IO String)  delayed strategy = runEff . evalStateLocal "Hey" $ do    r <- withEffToIO strategy $ \unlift -> pure $ unlift get    modify (++ "!!!")    pure r:}

    This doesn't work with the SeqUnlift strategy because when the returned action runs, State is no longer in scope:

    Example1 expression
    join $ delayed SeqUnlift*** Exception: version (...) /= storageVersion (0)...

    However, it does with the SeqForkUnlift strategy:

    Example1 expression
    join $ delayed SeqForkUnlift"Hey"
  • ConcUnlift !Persistence !Limit

    The concurrent strategy makes it possible for the unlifting function to be called in threads distinct from its creator. See Persistence and Limit settings for more information.

Instances5Eq, Ord, Show, Generic, Rep
datadata Persistence
#

Persistence setting for the ConcUnlift strategy.

Different functions require different persistence strategies. Examples:

  • Lifting pooledMapConcurrentlyN from the unliftio library requires the Ephemeral strategy as we don't want jobs to share environment changes made by previous jobs run in the same worker thread.

  • Lifting forkIOWithUnmask requires the Persistent strategy, otherwise the unmasking function would start with a fresh environment each time it's called.

Both cases come down to what happens when the unlifting function is called more than once in the same thread. If a thread calls it only once, the Persistence setting makes no observable difference.

Example 1

Consider a thread that modifies thread local state, then inspects it with a second call to the unlifting function:

Example4 expressions
import Control.Concurrentimport Control.Monadimport Effectfulimport Effectful.State.Dynamic
Example1 expression
:{  modifyThenGet :: UnliftStrategy -> IO Int  modifyThenGet strategy = runEff . evalStateLocal @Int 0 $ do    withEffToIO strategy $ \unlift -> do      result <- newEmptyMVar      void . forkIO $ do        unlift $ modify @Int (+1)        putMVar result =<< unlift (get @Int)      takeMVar result:}

With the Persistent strategy the unlifting function keeps the environment between the calls, so the second call sees the modification from the first one:

Example1 expression
modifyThenGet $ ConcUnlift Persistent (Limited 1)1

On the other hand, with Ephemeral each call to the unlifting function starts with a fresh copy of the environment, so the modification is silently lost:

Example1 expression
modifyThenGet $ ConcUnlift Ephemeral (Limited 2)0

This also showcases the limit meaning different things for the two settings: for the Persistent strategy it limits the number of threads the unlifting can happen in, for Ephemeral it limits the number of calls to the unlifting function.

Example 2

Consider a situation where a single worker thread runs multiple independent jobs:

Example1 expression
:{  twoJobs :: UnliftStrategy -> IO [Int]  twoJobs strategy = runEff . evalStateLocal @Int 0 $ do    withEffToIO strategy $ \unlift -> do      result <- newEmptyMVar      void . forkIO $ do        let job = unlift $ modify @Int (+1) >> get @Int        putMVar result =<< sequence [job, job]      takeMVar result:}

With Ephemeral both jobs start from the environment as it was when the unlifting function was created:

Example1 expression
twoJobs $ ConcUnlift Ephemeral Unlimited[1,1]

With Persistent the second job inherits changes made by the first one, even though the user would most likely expect them to be independent:

Example1 expression
twoJobs $ ConcUnlift Persistent Unlimited[1,2]

Constructors

  • Ephemeral

    Don't persist the environment between calls to the unlifting function in threads distinct from its creator.

  • Persistent

    Persist the environment between calls to the unlifting function within a particular thread.

Instances5Eq, Ord, Show, Generic, Rep
datadata Limit
#

Limit setting for the ConcUnlift strategy.

Constructors

  • Limited !Int

    Behavior dependent on the Persistence setting.

    For Ephemeral, it limits the amount of uses of the unlifting function in threads distinct from its creator to N. The unlifting function will create N copies of the environment when called N times and K+1 copies when called K < N times.

    For Persistent, it limits the amount of threads, distinct from the creator of the unlifting function, it can be called in to N. The amount of calls to the unlifting function within a particular threads is unlimited. The unlifting function will create N copies of the environment when called in N threads and K+1 copies when called in K < N threads.

  • Unlimited

    Unlimited use of the unlifting function.

Instances5Eq, Ord, Show, Generic, Rep
valuewithSeqEffToIO
  1. :: (HasCallStack, IOE :> es)
  2. => ((forall r. Eff es r -> IO r) -> IO a)

    Continuation with the unlifting function in scope.

  3. -> Eff es a
#

Create an unlifting function with the SeqUnlift strategy. For the general version see withEffToIO.

Note: usage of this function is preferrable to withRunInIO because of explicit unlifting strategy and better error reporting.

valuewithEffToIO
  1. :: (HasCallStack, IOE :> es)
  2. => UnliftStrategy
  3. -> ((forall r. Eff es r -> IO r) -> IO a)

    Continuation with the unlifting function in scope.

  4. -> Eff es a
#

Create an unlifting function with the given strategy.

Note: usage of this function is preferrable to withRunInIO because of explicit unlifting strategy and better error reporting.

Lifting

valueraise :: Eff es a -> Eff (e ': es) a
#

Lift an Eff computation into an effect stack with one more effect.

valueraiseWith
  1. :: HasCallStack
  2. => UnliftStrategy
  3. -> ((forall r. Eff (e ': es) r -> Eff es r) -> Eff es a)

    Continuation with the unlifting function in scope.

  4. -> Eff (e ': es) a
#

Lift an Eff computation into an effect stack with one more effect and create an unlifting function with the given strategy.

valuesubsume :: e :> es => Eff (e ': es) a -> Eff es a
#

Eliminate a duplicate effect from the top of the effect stack.

valueinject :: Subset subEs es => Eff subEs a -> Eff es a
#

Allow for running an effect stack subEs within es as long as subEs is a permutation (with possible duplicates) of a subset of es.

Generalizes raise and subsume.

Example3 expressions
data E1 :: Effectdata E2 :: Effectdata E3 :: Effect

It makes it possible to rearrange the effect stack however you like:

Example1 expression
:{  shuffle :: Eff (E3 : E1 : E2 : es) a -> Eff (E1 : E2 : E3 : es) a  shuffle = inject:}

It can also turn a monomorphic effect stack into a polymorphic one:

Example1 expression
:{  toPoly :: (E1 :> es, E2 :> es, E3 :> es) => Eff [E1, E2, E3] a -> Eff es a  toPoly = inject:}

Moreover, it allows for hiding specific effects from downstream:

Example1 expression
:{  onlyE1 :: Eff (E1 : es) a -> Eff (E1 : E2 : E3 : es) a  onlyE1 = inject:}
Example1 expression
:{  onlyE2 :: Eff (E2 : es) a -> Eff (E1 : E2 : E3 : es) a  onlyE2 = inject:}
Example1 expression
:{  onlyE3 :: Eff (E3 : es) a -> Eff (E1 : E2 : E3 : es) a  onlyE3 = inject:}

However, it's not possible to inject a computation into an incompatible effect stack:

Example1 expression
:{  coerceEs :: Eff es1 a -> Eff es2 a  coerceEs = inject:}......Couldn't match type ‘es1’ with ‘es2’...
classclass KnownPrefix es => Subset (subEs :: [Effect]) (es :: [Effect]) where
#

Provide evidence that subEs is a subset of es.

Instances3Subset
  • (KnownPrefix es, IsUnknownSuffixOf subEs es) => Subset subEs esDefined in effectful-core-2.7.1.2 · Effectful.Internal.Effect
  • KnownPrefix es => Subset '[] esDefined in effectful-core-2.7.1.2 · Effectful.Internal.Effect
  • (e :> es, Subset subEs es) => Subset (e ': subEs) esDefined in effectful-core-2.7.1.2 · Effectful.Internal.Effect

Re-exports

2 declarations
classclass Monad m => MonadIO (m :: Type -> Type) where
#

Monads in which IO computations may be embedded. Any monad built by applying a sequence of monad transformers to the IO monad will be an instance of this class.

Instances should satisfy the following laws, which state that liftIO is a transformer of monads:

Methods

  • liftIO :: IO a -> m a

    Lift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).

    Example
    import Control.Monad.Trans.State -- from the "transformers" library
    
    printState :: Show s => StateT s IO ()
    printState = do
      state <- get
      liftIO $ print state

    Had we omitted liftIO, we would have ended up with this error:

    • Couldn't match type ‘IO’ with ‘StateT s IO’
     Expected type: StateT s IO ()
       Actual type: IO ()

    The important part here is the mismatch between StateT s IO () and IO ().

    Luckily, we know of a function that takes an IO a and returns an (m a): liftIO, enabling us to run the program and see the expected results:

    > evalStateT printState "hello"
    "hello"
    
    > evalStateT printState 3
    3
    
Instances19MonadIO, …
classclass MonadIO m => MonadUnliftIO (m :: Type -> Type) where
#

Monads which allow their actions to be run in IO.

While MonadIO allows an IO action to be lifted into another monad, this class captures the opposite concept: allowing you to capture the monadic context. Note that, in order to meet the laws given below, the intuition is that a monad must have no monadic state, but may have monadic context. This essentially limits MonadUnliftIO to ReaderT and IdentityT transformers on top of IO.

Laws. For any function run provided by withRunInIO, it must meet the monad transformer laws as reformulated for MonadUnliftIO:

  • run . return = return
  • run (m >>= f) = run m >>= run . f

Instances of MonadUnliftIO must also satisfy the following laws:

Identity law

withRunInIO (\run -> run m) = m

Inverse law

withRunInIO (\_ -> m) = liftIO m

As an example of an invalid instance, a naive implementation of MonadUnliftIO (StateT s m) might be

withRunInIO inner =
  StateT $ \s ->
    withRunInIO $ \run ->
      inner (run . flip evalStateT s)

This breaks the identity law because the inner run m would throw away any state changes in m.

Methods

  • withRunInIO :: ((forall a. m a -> IO a) -> IO b) -> m b

    Convenience function for capturing the monadic context and running an IO action with a runner function. The runner function is used to run a monadic action m in IO.

Instances4MonadUnliftIO