4

我有代码

 main :: IO()
 main = runInputT defaultSettings loop          
 where                                        
   --loop :: InputT IO ()                     
   loop = do                                  
     minput <- getInputLine "$ "              
     case minput of                           
       Nothing -> return ()                   
       Just input -> process $ words input          
     loop                                     

其中 process 有类型定义

process :: [String] -> IO ()

但是我得到了错误:

• Couldn't match type ‘IO’ with ‘InputT m’                                                       
Expected type: InputT m ()                                                                     
  Actual type: IO ()                                                                           
• In the expression: process $ words input                                                       
In a case alternative: Just input -> process $ words input                                     
In a stmt of a 'do' block:                                                                     
  case minput of {                                                                             
    Nothing -> return ()                                                                       
    Just input -> process $ words input }

我想知道是否有人可以解释我做错了什么。我只想从 getInputLine 获取原始输入来做其他事情。

谢谢

4

1 回答 1

6

块中的所有语句do必须具有相同的类型(嗯,它们的类型必须具有相同的 monad)。在你的情况下,这是InputT IO something(单子是InputT IO)。

getInputLine "$ "有 type InputT IO (Maybe String),所以那部分没问题。

然后你有一个case表达式,这意味着所有分支都需要具有相同的类型。第一个分支是 just return (),它获取类型InputT IO ()。到目前为止一切都很好。

第二个分支是process $ words input。但这有 type IO (), not InputT IO (),这是编译器此时所期望的。

要解决这个问题:幸运的是,有一种简单的方法可以将类型的值转换(“提升”)IO xInputT IO x,这是liftIO函数:

Just input -> liftIO (process $ words input)

也就是说,liftIO :: IO a -> InputT IO a(实际上它比这更笼统:liftIO :: (MonadIO m) => IO a -> m a但这并不重要)。

于 2016-12-07T10:43:18.787 回答