Skip to content

adds a try function #16

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 1 commit into from
May 16, 2016
Merged
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
],
"dependencies": {
"purescript-eff": "^1.0.0-rc.1",
"purescript-maybe": "^1.0.0-rc.1"
"purescript-maybe": "^1.0.0-rc.1",
"purescript-either": "^1.0.0-rc.1",
"purescript-prelude": "^1.0.0-rc.1"
}
}
24 changes: 23 additions & 1 deletion src/Control/Monad/Eff/Exception.purs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ module Control.Monad.Eff.Exception
, throwException
, catchException
, throw
, try
) where

import Control.Monad.Eff (Eff)
import Control.Semigroupoid ((<<<))

import Data.Either (Either(Right, Left))
import Data.Maybe (Maybe(..))
import Data.Show (class Show)
import Prelude ((<$>), pure)

-- | This effect is used to annotate code which possibly throws exceptions
foreign import data EXCEPTION :: !
Expand Down Expand Up @@ -80,3 +82,23 @@ foreign import catchException
-- | `throwException <<< error`.
throw :: forall eff a. String -> Eff (err :: EXCEPTION | eff) a
throw = throwException <<< error

-- | Runs an Eff and returns eventual Exceptions as a `Left` value. If the
-- | computation succeeds the result gets wrapped in a `Right`.
-- |
-- | For example:
-- |
-- | ```purescript
-- | -- Notice that there is no EXCEPTION effect
-- | main :: forall eff. Eff (console :: CONSOLE, fs :: FS | eff) Unit
-- | main = do
-- | result <- try (readTextFile UTF8 "README.md")
-- | case result of
-- | Right lines ->
-- | Console.log ("README: \n" <> lines )
-- | Left error ->
-- | Console.error ("Couldn't open README.md. Error was: " <> show error)
-- | ```

try :: forall eff a. Eff (err :: EXCEPTION | eff) a -> Eff eff (Either Error a)
try action = catchException (pure <<< Left) (Right <$> action)