在readFile的catch子句中输入`if'时解析错误

时间:2017-03-30 00:27:02

标签: haskell exception-handling

我正在尝试在读取文件时处理异常,但我收到了消息

  

解析输入`if'

时的错误
readTxt = do
            {catch (read_file) fix_error;}
            where
                read_file = do
                {
                    f <- openFile "file.txt" ReadMode;
                    content <- hGetContents f;
                    putStrLn content;
                    hClose f;
                }   
                fix_error erro if = isDoesNotExistError erro
                    then do
                    {
                        putStr "Exception: file doesn't exists";
                        writeFile "file.txt" "First Line"
                    }
                else ioError erro 

我读到当我有if时,我需要thenelse子句返回相同的类型。我相信我这样做,所以我不知道为什么我收到错误消息

1 个答案:

答案 0 :(得分:1)

您在=的定义中交换了iffix_error

定义的语法是:

name args = body

if表达式的语法是:

if condition then true_branch else false_branch

您只需将这些结合起来:

fix_error erro = if isDoesNotExistError erro
               ----
  then do
    putStr "Exception: file doesn't exist"
    ...
  else ioError erro

或者使用警卫:

fix_error erro
  | isDoesNotExistError erro = do
    putStr "Exception: file doesn't exist"
    ...
  | otherwise = ioError erro

我省略了花括号和分号,但如果您愿意,可以包含它们。