xrjx      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdef g h i j k l m n o p q r s t u v w x y z { | } ~  Safe&',-;<=>?FQSTVLeft-edge deconstructionMNon-empty tree. Deconstruction operations make it more and more left-leaningThere is no tempty: use (tsingleton return), which works just the same. The names are chosen for compatibility with FastTCQueuesnoc: clearly constant-timeappend: clearly constant-time$Process the Left-edge deconstruction Trustworthy&'+,-;<=>?AFQSTV)3This class is used for emulating monad transformersRUsing overlapping instances here is OK since this class is private to this module!Find an index of an element in a list The element must exist This is essentially a compile-time computation. Using overlapping instances here is OK since this class is private to this module+A useful operator for reducing boilerplate. 9f :: [Reader Int, Writer String] <:: r => a -> Eff r b  is equal to If :: (Member (Reader Int) r, Member (Writer String) r) => a -> Eff r b #Typeclass that asserts that effect t& is contained inside the effect-list r.The FindElemb typeclass is necessary for implementation reasons and is not required for using the effect list./The data constructors of Union are not exportedStrong Sum (Existential with the evidence) is an open union t is can be a GADT and hence not necessarily a Functor. Int is the index of t in the list r; that is, the index of t in the universe r wExplicit type-level equality condition is a dirty hack to eliminate the type annotation in the trivial case, such as run (runReader () get).2There is no ambiguity when finding instances for Member t (a ': b ': r)(, which the second instance is selected.-The only case we have to concerned about is  Member t '[s]. But, in this case, values of definition is the same (if present), and the first one is chosen according to GHC User Manual, since the latter one is incoherent. This is the optimal choice.  Trustworthy&',-;<=>?FNQSTVS %Lifting: emulating monad transformers\The Eff monad (not a transformer!). It is a fairly standard coroutine monad where the type rC is the type of effects that can be handled, and the missing type a (from the type application) is the type of value that is returned. It is NOT a Free monad! There are no Functor constraints.The two constructors denote the status of a coroutine (client): done with the value of type a, or sending a request of type Union r with the continuation Arrs r b a. Expressed another way: an  can either be a value (i.e.,  case), or an effect of type  r producing another  (i.e.,  case). The result is that an + can produce an arbitrarily long chain of  r' effects, terminated with a pure value. Potentially, inline Union into EAn effectful function from a to bi that is a composition of one or more effectful functions. The paremeter r describes the overall effect.lThe composition members are accumulated in a type-aligned queue. Using a newtype here enables us to define Category and Arrow instances.QEffectful arrow type: a function from a to b that also does effects denoted by rCconvert single effectful arrow into composable type. i.e., convert  to OApplication to the `generalized effectful function' Arrs r b w, i.e., convert  to Syntactic sugar for Lift a function to an arrowThe identity arrowArrow composition Common pattern: append  to !:Compose effectful arrows (and possibly change the effect!)":Compose effectful arrows (and possibly change the effect!)#MSend a request and wait for a reply (resulting in an effectful computation).$9Get the result from a pure (i.e. no effects) computation.]The type of run ensures that all effects must be handled: only pure computations can be run.%RA convenient pattern: given a request (open union), either handle it or relay it.&Parameterized handle_relay'WAdd something like Control.Exception.catches? It could be useful for control with cut.sIntercept the request and possibly reply to it, but leave it unhandled (that's why we use the same r all throuout)(Embeds a less-constrained 2 into a more-constrained one. Analogous to MTL's ).)4We make the Lift layer to be unique, using SetMember*_The handler of Lift requests. It is meant to be terminal: we only allow a single Lifted Monad.bEff is still a monad and a functor (and Applicative) (despite the lack of the Functor constraint)As the name suggests,  also has an Arrow instance.- can be composed and have a natural identity. !"#$%&'()*Safe&'+,-;<=>?FQSTVW+Same as , but with additional  constraint,1A convenient alias to 'SetMember Lift (Lift m) r'-4Catching of dynamic exceptions See the problem in 4http://okmij.org/ftp/Haskell/misc.html#catch-MonadIO)*+,-,+)*-Safe&',-;<=>?FQSTVX !"#$%&'($%&'(# !"Safe&',-;<=>?FQSTVZ*$$Safe&',-;<=>?FQSTVn: .The Writer monadIn MTL's Writer monad, the told value must have a |Monoid| type. Our writer has no such constraints. If we write a |Writer|-like interpreter to accumulate the told values in a monoid, it will have the |Monoid w| constraint then0Write a new value.1#Transform the state being produced.2jHandle Writer requests, using a user-provided function to accumulate values, hence no Monoid constraints.3:Handle Writer requests, using a List to accumulate values.4EHandle Writer requests, using a Monoid instance to accumulate values.5:Handle Writer requests by taking the first value provided.66Handle Writer requests by overwriting previous values.7zHandle Writer requests, using a user-provided function to accumulate values and returning the final accumulated values.8hHandle Writer requests, using a List to accumulate values and returning the final accumulated values.9sHandle Writer requests, using a Monoid instance to accumulate values and returning the final accumulated values.:lHandle Writer requests by taking the first value provided and and returning the final accumulated values.;dHandle Writer requests by overwriting previous values and returning the final accumulated values../0123456789:;./01256347:;89./Safe&',-;<=>?FQSTV =The Writer monadIn MTL's Writer monad, the told value must have a |Monoid| type. Our writer has no such constraints. If we write a |Writer|-like interpreter to accumulate the told values in a monoid, it will have the |Monoid w| constraint then?Write a new value.@#Transform the state being produced.AjHandle Writer requests, using a user-provided function to accumulate values, hence no Monoid constraints.B:Handle Writer requests, using a List to accumulate values.CEHandle Writer requests, using a Monoid instance to accumulate values.D:Handle Writer requests by taking the first value provided.E6Handle Writer requests by overwriting previous values.FzHandle Writer requests, using a user-provided function to accumulate values and returning the final accumulated values.GhHandle Writer requests, using a List to accumulate values and returning the final accumulated values.HsHandle Writer requests, using a Monoid instance to accumulate values and returning the final accumulated values.IlHandle Writer requests by taking the first value provided and and returning the final accumulated values.JdHandle Writer requests by overwriting previous values and returning the final accumulated values.=>?@ABCDEFGHIJ=>?@ADEBCFIJGH=>Safe&',-3;<=>?FQSTVLTrace effect for debuggingNPrint a string as a trace.OSRun a computation producing Traces. The handler for IO request: a terminal handlerLMNOLMNOLMSafe&',-;<=>?FQSTV PThe Reader monadThe request for a value of type e from the current environment This can be expressed as a GADT because the type of values returned in response to a (Reader e a) request is not any a; we expect in reply the value of type eM, the value from the environment. So, the return type is restricted: 'a ~ e'One can also define this as $data Reader e v = (e ~ v) => Reader 9^ without GADTs, using explicit coercion as is done here. #newtype Reader e v = Reader (e->v) ^ In the latter case, when we make the request, we make it as Reader id. So, strictly speaking, GADTs are not really necessary.RgGet the current value from a Reader. The signature is inferred (when using NoMonomorphismRestriction).SbThe handler of Reader requests. The return type shows that all Reader requests are fully handled.TLocally rebind the value in the dynamic environment This function is like a relay; it is both an admin for Reader requests, and a requestor of themU>Request the environment value using a transformation function.PQRSTUPQRTUSPQ Trustworthy&',-;<=>?FQSTV WAn encapsulated State handler, for transactional semantics The global state is updated only if the transactionState finished successfullyY State, strictInitial design: The state request carries with it the state mutator function We can use this request both for mutating and getting the state. But see below for a better design! 3data State s v where State :: (s->s) -> State s sIn this old design, we have assumed that the dominant operation is modify. Perhaps this is not wise. Often, the reader is most nominant.ASee also below, for decomposing the State into Reader and Writer! The conventional design of State\BReturn the current value of the state. The signatures are inferred]Write a new value of the state._Run a State effect`$Transform the state with a function.a/Run a State effect, discarding the final state.b.Run a State effect and return the final state.dA different representation of State: decomposing State into mutation (Writer) and Reading. We don't define any new effects: we just handle the existing ones. Thus we define a handler for two effects together._Effect incorporating State Initial state0Effect containing final state and a return valueWXY[Z\]^_`abcdYZ[e\]^_`abWXcdWXYZ[ Safe&',-;<=>?FQSTV7fThe Reader monadThe request for a value of type e from the current environment This can be expressed as a GADT because the type of values returned in response to a (Reader e a) request is not any a; we expect in reply the value of type eM, the value from the environment. So, the return type is restricted: 'a ~ e'One can also define this as $data Reader e v = (e ~ v) => Reader 9^ without GADTs, using explicit coercion as is done here. #newtype Reader e v = Reader (e->v) ^ In the latter case, when we make the request, we make it as Reader id. So, strictly speaking, GADTs are not really necessary.hgGet the current value from a Reader. The signature is inferred (when using NoMonomorphismRestriction).ibThe handler of Reader requests. The return type shows that all Reader requests are fully handled.jLocally rebind the value in the dynamic environment This function is like a relay; it is both an admin for Reader requests, and a requestor of them.k>Request the environment value using a transformation function.fghijkfghjkifg  Trustworthy&',-;<=>?FQSTV mState, lazy (i.e., on-demand)Extensible effects make it clear that where the computation is delayed (which I take as an advantage) and they do maintain the degree of extensibility (the delayed computation must be effect-closed, but the whole computation does not have to be).qBReturn the current value of the state. The signatures are inferredrWrite a new value of the state.uRun a State effectv$Transform the state with a function.w/Run a State effect, discarding the final state.x.Run a State effect and return the final state.yA different representation of State: decomposing State into mutation (Writer) and Reading. We don't define any new effects: we just handle the existing ones. Thus we define a handler for two effects together.zBackwards state The overall state is represented with two attributes: the inherited getAttr and the synthesized putAttr. At the root node, putAttr becomes getAttr, tying the knot. As usual, the inherited attribute is the argument (i.e., the  environment?) and the synthesized is the result of the handler |go| below.{A different notion of  backwards9 is realized if we change the Put handler slightly. How?Another implementation, exploring Haskell's laziness to make putAttr also technically inherited, to accumulate the sequence of updates. This implementation is compatible with deep handlers, and lets us play with different notions of  backwardnessu Initial stateEffect incorporating State0Effect containing final state and a return valuemponqrstuvwxyz{mnop|qrstuvwxyz{mnop  Trustworthy&',-;<=>?FQSTV }An encapsulated State handler, for transactional semantics The global state is updated only if the transactionState finished successfully State, lazyInitial design: The state request carries with it the state mutator function We can use this request both for mutating and getting the state. But see below for a better design! 3data State s v where State :: (s->s) -> State s sIn this old design, we have assumed that the dominant operation is modify. Perhaps this is not wise. Often, the reader is most nominant.ASee also below, for decomposing the State into Reader and Writer! The conventional design of StateBReturn the current value of the state. The signatures are inferredWrite a new value of the state.$Run a state effect. compared to the runStateL function, this is implemented naively and is expected to perform slower.CRun a State effect. This variant is a bit optimized compared to  runState'.$Transform the state with a function./Run a State effect, discarding the final state..Run a State effect and return the final state.A different representation of State: decomposing State into mutation (Writer) and Reading. We don't define any new effects: we just handle the existing ones. Thus we define a handler for two effects together. Initial stateEffect incorporating State0Effect containing final state and a return value}~}~}~ Safe&',-;<=>?CFQSTVELift values to an effect. You can think this is a generalization of Lift.Lift a value to a monad.2Convert values using given interpreter to effects. Safe&',-;<=>?FQSTVDefine data using GADTs.7Then, implements interpreters from the data to effects.Safe&',-;<=>?FQSTV>IA different implementation, more directly mapping to MonadPlus interfaceAn interpreter The following is very simple, but leaks a lot of memory The cause probably is mapping every failure to empty It takes then a lot of timne and space to store those emptyA different implementation, more involved but faster and taking much less (100 times) less memory. The benefit of the effect framework is that we can have many interpreters._Same as makeChoiceA, except it has the type hardcoded. Required for MonadBaseControl instance. Safe&',-3;<=>?FQSTVw Create unique Enumerable values.6Produce a value that has not been previously produced.&Run an effect requiring unique values.Safe&',-;<=>?FQSTV2 Exceptions'exceptions of the type e; no resumptionEThrow an exception in an effectful computation. The type is inferred.Throw an exception in an effectful computation. The type is unit, which suppresses the ghc-mod warning "A do-notation statement discarded a result of type"?Makes an effect fail, preventing future effects from happening.2Run a computation that might produce an exception.<Runs a failable effect, such that failed computation return  , and  the return value on success.Run a computation that might produce exceptions, and give it a way to deal with the exceptions that come up. The handler is allowed to rethrow the exceptionsAdd a default value (i.e. failure handler) to a fallible computation. This hides the fact that a failure happened.iRun a computation until it produces an exception, and convert and throw that exception in a new context.6Treat Lefts as exceptions and Rights as return values. in a lifted MonadLift a maybe into the ! effect, causing failure if it's . in a lifted MonadIgnores a failure event. Since the event can fail, you cannot inspect its return type, because it has none on failure. To inspect it, use .The fallible computation."The computation to run on failure.Safe&',-;<=>?FQSTVCs -an effectful function that can throw an error >tooBig = do when (i > 100) $ throwError $ show i return i run the tooBig effect based on a provided Int. (runTooBig i = run . runError $ tooBig i  runTooBig 1Right 1 runTooBig 200 Left "200":an effectul computation using state. The state is of type [Int]. This function takes the head off the list, if it is there and return it. If state is the empty list, then it stays the same and returns Nothing. |popState = do stack <- get case stack of [] -> return Nothing (x : xs) -> do put xs return $ Just x qrun the popState effectful computation based on initial state. The result-type is the result of the computation  Maybe Int8 together with the state at the end of the computation [Int] .runPopState xs = run . runState xs $ popState runPopState [1, 2, 3](Just 1,[2,3])runPopState [] (Nothing,[])7an effect that returns a number one more than the given noneMore = do x <- ask -- query the environment return $ x + 1 -- add one to the asked value and return it Run the oneMore1 effectful function by giving it a value to read. +runOneMore i = run . runReader i $ oneMore  runOneMore 12/An effectful computation with multiple effects:A value gets read2an error can be thrown depending on the read valuestate gets read and transformed)All these effects are composed using the Eff- monad using the corresponding Effect types. something = do readValue :: Float <- ask -- read a value from the environment when (readValue < 0) $ throwError readValue -- if the value is negative, throw an error modify (l -> (round readValue :: Integer) : l) -- add the rounded read element to the list currentState :: [Integer] <- get -- get the state after the modification return $ sum currentState -- sum the elements in the list and return that Run the someting effectful computation given in the previous function. The handlers apply from bottom to top - so this is the reading direction. runSomething1 initialState newValue = run . -- run the Eff-monad with no effects left runError . -- run the error part of the effect. This introduces the Either in the result. runState initialState . -- handle the state-effect providing an initial state giving back a pair. runReader newValue $ -- provide the computation with the dynamic value to read/ask for something -- the computation - function runSomething1 [] (-0.5) Left (-0.5)runSomething1 [2] 1.3Right (3,[1,2])Run the  something] effectful computation given above. This has an alternative ordering of the effect-handlers.QThe used effect-handlers are the same are used in slightly different order: The runState and runErrorR methods are swapped, which results in a different output type and run-semantics. runSomething1 initialState newValue = run . runState initialState . runError . runReader newValue $ something -- the computation - function runSomething2 [4] (-2.4)(Left (-2.4),[4])runSomething2 [4] 5.9(Right 10,[6,4])-fghijk}~ Safe&'+,-;<=>?FQSTVLg JThe datatype for the example from the paper. See the tests for the example0specialization to tell the type of the exceptionMultiple Reader effects2Write the elements of a list of numbers, in order.+Add a list of numbers to the current state.:Write a list of numbers and add them to the current state.Sum a list of numbers.aSafely get the last element of a list. Nothing for empty lists; Just the last element otherwise.&Get the last element and sum of a listSafe&',-3;<=>?FQSTVWNStatus of a thread: done or reporting the value of the type a (For simplicity, a co-routine reports a value but accepts unit)Type parameter r# is the effect we're yielding from.Type parameter a is the type that is yielded.Type parameter wO is the type of the value returned from the coroutine when it has completed.QCo-routines The interface is intentionally chosen to be the same as in transf.hsq| The yield request: reporting a value of type e and suspending the coroutine. Resuming with the value of type b2Yield a value of type a and suspend the coroutine.%Launch a thread and report its statusSafe&',-;<=>?FQSTVaNon-determinism (choice)choose lst non-deterministically chooses one value from the lst choose [] thus corresponds to failure Unlike Reader, Choose is not a GADT because the type of values returned in response to a (Choose a) request is just a, without any constraints.fchoose lst non-deterministically chooses one value from the lst choose [] thus corresponds to failure3MonadPlus-like operators are expressible via choose3MonadPlus-like operators are expressible via choose4Run a nondeterministic effect, returning all values.3MonadPlus-like operators are expressible via chooseSafe&',-;<=>?FQSTVjIThe interpreter -- it is like reify . reflect with a twist. Compare this implementation with the huge implementation of call in Hinze 2000 (Figure 9). Each clause corresponds to the axiom of call or cutfalse. All axioms are covered.The code clearly expresses the intuition that call watches the choice points of its argument computation. When it encounteres a cutfalse request, it discards the remaining choicepoints. It completely handles CutFalse effects but not non-determinism !"#$%&'()*++,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTFGHIJKLMNOPQRSTUUVWXYZ[\]T^^_`abcdefghijT X Y Z [ \ ] T k ` a l b c m d e f g h j n o T ^ ^ _ ` a b c d e f g h i j T p q r s t u v w x yz{|}~TTTT/1extensible-effects-3.0.0.0-GMfaDAYkPTL7QUdW5LEzWkData.OpenUnionControl.Eff.LiftControl.Eff.ExtendControl.Eff.Writer.StrictControl.Eff.Writer.LazyControl.Eff.TraceControl.Eff.Reader.StrictControl.Eff.State.StrictControl.Eff.Reader.LazyControl.Eff.State.OnDemandControl.Eff.State.LazyControl.Eff.OperationalControl.Eff.Operational.ExampleControl.Eff.NdetEffControl.Eff.FreshControl.Eff.ExceptionControl.Eff.QuickStartControl.Eff.ExampleControl.Eff.CoroutineControl.Eff.ChooseControl.Eff.Cut Data.FTCQueueControl.Eff.Internal Control.Eff SetMember<::MemberinjprjUniondecompweaken$fFindElem[]t[]$fFindElem[]t:$fFindElem[]t:0 $fMembertr $fMembert: $fEQUkBoolabp$fEQUkBoolaaTrue$fMemberU'kFalsetagt:$fMemberU'kTruetagtag:$fSetMemberktagt1:LiftEffValEArrsArrfirstsingleKqApp^$arridentcomp^|>qCompqCompssendrun handle_relayhandle_relay_s interposeraiseliftrunLift LiftedBaseLifted catchDynEWriterTelltellcensor runWriter runListWriterrunMonoidWriterrunFirstWriter runLastWriter execWriterexecListWriterexecMonoidWriterexecFirstWriterexecLastWriter$fMonadBaseControlmEffTracetracerunTraceReaderAskask runReaderlocalreaderTxStateStateGetPutgetput runState'runStatemodify evalState execStatetransactionState runStateR OnDemandStateDelayonDemand runStateBack0 runStateBackProgram Singleton singleton runProgramJailPrintScanprogadventIO adventPureNdetEffMZeroMPlus makeChoiceA0 makeChoiceA makeChoiceLstmsplitifteonce$fMonadPlusEff$fAlternativeEffFreshfresh runFresh'FailExc throwError throwError_dierunErrorrunFail catchErroronFail rethrowError liftEither liftEitherM liftMaybe liftMaybeM ignoreFailtooBig runTooBigpopState runPopStateoneMore runOneMore something runSomething1 runSomething2MoveTooBig runErrBigsum2writeAllsumAll writeAndAddsumEfflastEff lastAndSumhandUphandDown $fEqTooBig $fShowTooBigYDoneYieldyieldrunCChoosechoosemzero'mplus' makeChoiceCutFalsecutfalsecallViewLFTCQueue tsingleton|>><viewlMaptviewlTOne:|LeafNodeEQUFindElemelemNoPunP $fFunctorEff $fArrowArrs$fCategoryTYPEArrs,monad-control-1.0.2.3-2muMHtg8mYx8DwPZ9oyBonControl.Monad.Trans.ControlMonadBaseControlReplacebaseGHC.BaseNothingJust