7

鉴于下面的概念验证代码,我希望能够以某种方式执行我的foo函数,能够输出字符串,并且有可能在monad-transformerPaul!中获取其返回值,而无需在.InputTunsafePerformIOrunExceptT

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!"

我在这里遗漏了一些明显的东西吗?

4

1 回答 1

11

由于InputT IOis a 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改为使用。

于 2015-01-20T19:33:49.410 回答