Skip to content

How to implement early return in effectful? #285

Answered by arybczak
kedashoe asked this question in Q&A
Discussion options

You must be logged in to vote

You should piggyback on the Error effect, since EarlyReturn is Error without CatchError:

import Effectful
import Effectful.Dispatch.Dynamic
import Effectful.Error.Static

data EarlyReturn r :: Effect where
  ReturnWith :: r -> EarlyReturn r m a

type instance DispatchOf (EarlyReturn r) = Dynamic

returnWith
  :: (HasCallStack, EarlyReturn r :> es)
  => r
  -> Eff es a
returnWith = send . ReturnWith

runEarlyReturn :: Show r => Eff (EarlyReturn r : es) a -> Eff es (Either (CallStack, r) a)
runEarlyReturn = reinterpret_ runError $ \case
  ReturnWith r -> throwError r

You can also do runErrorNoCallStack if you don't want a call stack in the result (or throwError_ if you don't want to impose …

Replies: 4 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by arybczak
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@ocharles
Comment options

@kedashoe
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants