鉴于下面的概念代码证明,我希望能够以某种方式执行我的foo
函数,并能够输出字符串Paul!
以及获取其返回值的可能性InputT
之后unsafePerformIO
monad-transformer未使用runExceptT
删除IO包装器。
import Control.Monad.Except
import System.IO.Unsafe (unsafePerformIO)
import System.Console.Haskeline
type ErrorWithIO = ExceptT String IO
foo :: String -> ErrorWithIO String
foo "paul" = do liftIO $ putStrLn "Paul!"
return "OK!"
foo _ = throwError "ERROR!"
runRepl :: IO ()
runRepl = runInputT defaultSettings $ loop
loop :: InputT IO ()
loop = do
line <- getInputLine "> "
case line of
Nothing -> return ()
Just input -> do return $ putStrLn "asd"
case unsafePerformIO $ runExceptT $ foo input of
Left err -> outputStrLn err >> loop
Right res -> do
x <- outputStrLn . show $ res
loop
main :: IO ()
main = runRepl >> putStrLn "Goodbye!"
我错过了一些明显的东西吗?
答案 0 :(得分:11)
由于InputT IO
是MonadIO
,您可以liftIO
使用此类型:
liftIO :: IO a -> InputT IO a
所以,
do ...
x <- liftIO $ runExceptT $ foo input
case x of
Left err -> ...
Right res -> ...
或者,请改用Control.Monad.Trans.lift
。