Skip to content

Add bracket #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 21, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/Control/Monad/Error/Class.purs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Control.Monad.Error.Class where
import Prelude

import Data.Maybe (Maybe(..))
import Data.Either (Either(..))
import Data.Either (Either(..), either)

-- | The `MonadError` type class represents those monads which support errors via
-- | `throwError` and `catchError`.
Expand Down Expand Up @@ -54,3 +54,19 @@ instance monadErrorMaybe :: MonadError Unit Maybe where
throwError = const Nothing
catchError Nothing f = f unit
catchError (Just a) _ = Just a

-- | Make sure that a resource is cleaned up in the event of an exception. The
-- | release action is called regardless of whether the body action throws or
-- | returns.
withResource
:: forall e m r a
. MonadError e m
=> m r
-> (r -> m Unit)
-> (r -> m a)
-> m a
withResource acquire release kleisli = do
resource <- acquire
result <- (Right <$> kleisli resource) `catchError` (pure <<< Left)
release resource
either throwError pure result