解开从输入getInputLine结果(unwrap getInputLine result fro

2019-09-25 18:43发布

我碰到一个结果getInputline ,其类型为:

(MonadException m) => IO String -> InputT m (Maybe String)

我想获得只是Maybe String的一部分。 我很清楚,一般没有办法剥夺一个单子,在解释这个答案 (以及同样的问题其他的答案)。 然而,因为我正在做内部InputT ,我想这是可能的,如建议在这里 。 但是,我不能只用liftIO ,作为回答表明,由于IO是一个内部StateT

loop :: Counter -> InputT (StateT [String] IO) ()    
loop c = do
        minput <- getLineIO $ in_ps1 $ c
        case minput of
          Nothing -> outputStrLn "Goodbye."
          Just input -> (process' c input) >> loop c      

getLineIO :: (MonadException m) => IO String -> InputT m (Maybe String)
getLineIO ios = do
    s <- liftIO ios
    getInputLine s

process' :: Counter -> String -> InputT (StateT [String] IO) ()
[...]

我得到的错误:

Main.hs:81:15:
    No instance for (MonadException (StateT [String] IO))
      arising from a use of ‘getLineIO’
    In the expression: getLineIO
    In a stmt of a 'do' block: minput <- getLineIO $ in_ps1 $ c
    In the expression:
      do { minput <- getLineIO $ in_ps1 $ c;
           case minput of {
             Nothing -> outputStrLn "Goodbye."
             Just input -> (process' c input) >> loop c } }

如果我删除getLineIO和使用getInputLine直接,按@ chepner的建议是:

loop :: Counter -> InputT (StateT [String] IO) ()
loop c = do
    minput <- (in_ps1 c) >>= getInputLine
    case minput of
      Nothing -> outputStrLn "Goodbye."
      Just input -> (process' c input) >> loop c

我发现了一个错误:

Main.hs:81:16:
    Couldn't match type ‘IO’ with ‘InputT (StateT [String] IO)’
    Expected type: InputT (StateT [String] IO) String
      Actual type: IO String
    In the first argument of ‘(>>=)’, namely ‘(in_ps1 c)’
    In a stmt of a 'do' block: minput <- (in_ps1 c) >>= getInputLine

完整的代码可以发现在这里 ,可以找到什么我想要做的解释在这里 。

文章来源: unwrap getInputLine result from Input