Wol*_*lfe 4 monads haskell haskeline
我有代码
 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                                     
Run Code Online (Sandbox Code Playgroud)
进程具有类型定义
process :: [String] -> IO ()
Run Code Online (Sandbox Code Playgroud)
但是我得到错误:
• 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 }
Run Code Online (Sandbox Code Playgroud)
我想知道是否有人可以解释我做错了什么.我只想从getInputLine生成输入来做其他事情.
谢谢
do块中的所有语句必须具有相同的类型(嗯,类型中必须具有相同的monad).在你的情况下,这是InputT IO something(与monad一起InputT IO).
getInputLine "$ "有类型InputT IO (Maybe String),所以该部分是可以的.
然后你有一个case表达式,这意味着所有分支都需要具有相同的类型.第一个分支就是return (),它获得了类型InputT IO ().到目前为止都很好.
第二个分支是process $ words input.但是这有类型IO (),而不是InputT IO ()编译器在此时期望的类型.
为了解决这个问题:幸运的是,以类型的值转换("提升"),一个简单的方法IO x来InputT IO x,这是liftIO功能:
Just input -> liftIO (process $ words input)
Run Code Online (Sandbox Code Playgroud)
也就是说,liftIO :: IO a -> InputT IO a(实际上它比这更普遍:liftIO :: (MonadIO m) => IO a -> m a但这并不重要).
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           179 次  |  
        
|   最近记录:  |