Skip to content

Instantly share code, notes, and snippets.

@michaelpj
Last active May 1, 2024 10:01
Show Gist options
  • Save michaelpj/75cf297edea5949a38c1f1fa5fc0c47c to your computer and use it in GitHub Desktop.
Save michaelpj/75cf297edea5949a38c1f1fa5fc0c47c to your computer and use it in GitHub Desktop.
Bluefin bracket fun
-- A stateful funciton with a counter and a boolean saying if it has terminated
-- We use bracket to always set the termination boolean, even if there is an exception
-- in the initial action.
ghci> let f st act =
bracket
(pure ())
(\_ -> modify st (\(c,fin) -> (c, True)))
(\_ -> do { act; modify st (\(c, fin) -> ((c + 1), fin)) })
ghci> :t f
f :: (st :> es, Num a1) =>
State (a1, Bool) st -> Eff es a2 -> Eff es ()
-- Normal execution, the counter is incremented and the termination bool is set
ghci> runPureEff $ runState (0, False) $ \st -> f st (pure ())
((),(1,True))
-- Exceptional execution, the counter is not incremented but the termination bool is still set
ghci> runPureEff $ runState (0, False) $ \st -> try $ \ex -> f st (throw ex 42)
(Left 42,(0,True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment