Skip to content

Commit d8d76f1

Browse files
authored
Merge pull request #85 from rightfold/master
Add bracket
2 parents ad972e4 + 3dd9835 commit d8d76f1

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/Control/Monad/Error/Class.purs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ module Control.Monad.Error.Class where
55
import Prelude
66

77
import Data.Maybe (Maybe(..))
8-
import Data.Either (Either(..))
8+
import Data.Either (Either(..), either)
99

1010
-- | The `MonadError` type class represents those monads which support errors via
1111
-- | `throwError` and `catchError`.
@@ -54,3 +54,19 @@ instance monadErrorMaybe :: MonadError Unit Maybe where
5454
throwError = const Nothing
5555
catchError Nothing f = f unit
5656
catchError (Just a) _ = Just a
57+
58+
-- | Make sure that a resource is cleaned up in the event of an exception. The
59+
-- | release action is called regardless of whether the body action throws or
60+
-- | returns.
61+
withResource
62+
:: forall e m r a
63+
. MonadError e m
64+
=> m r
65+
-> (r -> m Unit)
66+
-> (r -> m a)
67+
-> m a
68+
withResource acquire release kleisli = do
69+
resource <- acquire
70+
result <- (Right <$> kleisli resource) `catchError` (pure <<< Left)
71+
release resource
72+
either throwError pure result

0 commit comments

Comments
 (0)