在InputT monad中的Haskeline中执行简单的IO,而不必求助于unsafePerformIO

时间:2015-01-20 19:22:35

标签: haskell monad-transformers haskeline

鉴于下面的概念代码证明,我希望能够以某种方式执行我的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!"

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:11)

由于InputT IOMonadIO,您可以liftIO使用此类型:

liftIO :: IO a -> InputT IO a

所以,

do ...
   x <- liftIO $ runExceptT $ foo input
   case x of
     Left err  -> ...
     Right res -> ...

或者,请改用Control.Monad.Trans.lift