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 :: [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は同じ型でなければなりません (つまり、その型に同じモナドがなければなりません)。あなたの場合、これはInputT IO something(モナドがInputT IO)です。

getInputLine "$ "型がありますInputT IO (Maybe String)ので、その部分はOKです。

次にcase式があります。これは、すべてのブランチが同じタイプである必要があることを意味します。最初のブランチは justreturn ()で、タイプを取得しInputT IO ()ます。これまでのところすべて順調です。

2 番目のブランチはprocess $ words input. しかし、これは型IO ()ではなくInputT IO ()、コンパイラーがこの時点で予期しているものです。

これを修正するには: 幸いなことに、 type の値を に変換 (「リフト」) する簡単な方法IO xがあります。InputT 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 に答える