3

我正在尝试在 Haskell 中读取文件并捕获异常但无法正常工作。代码如下所示:

     module Main where
    import System.Environment
    import System.IO
    import System.Exit

    main = do
        x:xs <- getArgs
        case length(x:xs) of
            2 -> do catch (readFile x)
                        (\_ -> do   putStrLn ("Error on reading file: " ++ x) 
                                    getLine
                                    exitWith ExitSuccess)
            _ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>
                exitFailure

我得到这个错误:

Couldn't match expected type `IO String
                              -> (ExitCode -> IO a)
                              -> ExitCode
                              -> IO String'
       against inferred type `IO ()'
In the expression:
    putStrLn
      ("Error on reading file: " ++ x) getLine exitWith ExitSuccess
In the expression:
    do { putStrLn
           ("Error on reading file: " ++ x) getLine exitWith ExitSuccess }
In the second argument of `catch', namely
    `(\ _ -> do { putStrLn
                    ("Error on reading file: " ++ x) getLine exitWith ExitSuccess })'

你能给我一个提示吗?谢谢

4

2 回答 2

3

你在第 13 行有一个额外的>>(或一个额外的):do

_ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>

应该:

_ -> do putStrLn ("Run this way: ./projekt inputFile RE")

或者:

_ -> putStrLn ("Run this way: ./projekt inputFile RE") >> exitFailure

完整代码:

main = do
l@(x:xs) <- getArgs
case length l of
    2 -> do catch (readFile x) $ \_ -> do
            putStrLn $ "Error on reading file: " ++ x
            getLine
            exitWith ExitSuccess
    _ -> do putStrLn $ "Run this way: ./projekt inputFile RE"
            exitFailure
于 2011-03-07T21:52:09.077 回答
0

检查你的缩进。

尽管粘贴后的代码看起来没问题,但错误消息表明getLineexitWith ExitSuccess的缩进可能比putStrLn上面的更远。也许这是一个空格 -v- 选项卡问题?

于 2011-03-07T22:34:37.730 回答