Introduce Run monad
A monad for nice, pure exceptions. I want to avoid working with IO exceptions as much as possible.
This commit is contained in:
parent
1b8680004e
commit
b554d80aa9
4 changed files with 96 additions and 61 deletions
|
|
@ -1,17 +1,32 @@
|
|||
module Mima.IO
|
||||
( parseFile
|
||||
( Run
|
||||
, doRun
|
||||
, failWith
|
||||
, parseFile
|
||||
) where
|
||||
|
||||
import Control.Monad.Trans.Class
|
||||
import Control.Monad.Trans.Except
|
||||
import qualified Data.Text.IO as T
|
||||
import Text.Megaparsec
|
||||
|
||||
import Mima.Parser.Common
|
||||
|
||||
parseFile :: Parser a -> FilePath -> IO (Maybe a)
|
||||
type Run a = ExceptT String IO a
|
||||
|
||||
doRun :: Run () -> IO ()
|
||||
doRun r = do
|
||||
result <- runExceptT r
|
||||
case result of
|
||||
Left errorMsg -> putStrLn errorMsg
|
||||
Right () -> pure ()
|
||||
|
||||
failWith :: String -> Run a
|
||||
failWith = except . Left
|
||||
|
||||
parseFile :: Parser a -> FilePath -> Run a
|
||||
parseFile parser filepath = do
|
||||
content <- T.readFile filepath
|
||||
content <- lift $ T.readFile filepath
|
||||
case parse parser filepath content of
|
||||
Right a -> pure $ Just a
|
||||
Left errorBundle -> do
|
||||
putStrLn $ errorBundlePretty errorBundle
|
||||
pure Nothing
|
||||
Right a -> pure a
|
||||
Left errorBundle -> failWith $ errorBundlePretty errorBundle
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue