加载错误无法匹配预期的类型\'IO可能是字符串\'时该怎么办

问题描述

||
module REPL(REPL(..),repl) where
import qualified Control.Exception as E
import System.Console.Readline(readline,addHistory)

data REPL s = REPL {
    repl_init :: IO (String,s),-- prompt and initial state
    repl_eval :: s -> String -> IO (Bool,-- quit flag and new state
    repl_exit :: s -> IO ()
    }

repl :: REPL s -> IO ()
repl p = do
    (prompt,state) <- repl_init p
    let loop s = (do
        mline <- readline prompt
        case mline of
        nothing -> loop s
        Just line -> do
            (quit,s\') <- repl_eval p s line
            if quit then
            repl_exit p s\'
             else do
            addHistory line
            loop s\'
        ) E.catch undefined (\\(e :: E.someException) -> putStrLn \"Handled exception!\"
        )
    loop state
输出
REPL.hs:21:5:
    Couldn\'t match expected type `IO (Maybe String)\'
           against inferred type `t -> Maybe String\'
    In a stmt of a \'do\' expression: mline <- readline prompt
    In the expression:
        (do { mline <- readline prompt;
              case mline of {
                nothing -> loop s
                Just line
                  -> do { (quit,s\') <- repl_eval p s line;
                          .... } } })
          E.catch
          undefined
          (\\ (e :: E.someException) -> putStrLn \"Handled exception!\")
    In the deFinition of `loop\':
        loop s = (do { mline <- readline prompt;
                       case mline of {
                         nothing -> loop s
                         Just line -> do { ... } } })
                   E.catch
                   undefined
                   (\\ (e :: E.someException) -> putStrLn \"Handled exception!\")
    

解决方法

从上一个问题开始,您已经删除了
E.catch
语句周围的反引号`。我对这个问题的回答没有使用反引号,因为我没有打电话给
catch
中缀。您可以使用不带反引号的catch后缀:
let loop s = E.catch (do ...) (\\(e :: E.SomeException) -> ...)
或者您可以在反引号中使用catch infix:
let loop s = (do ...) `E.catch` (\\(e :: E.SomeException) -> ...)
同样,
undefined
只是为了在GHCi REPL上举一个例子而强加了一个例外-它代替了代码中的
(do ..)
语句。