0

I'm trying handling an exception when I read a file but I'm receiving the message

parse error on input `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 

I read that when I have an if I need that the then and else clauses return the same type. I believe that I'm doing this, so I don't know why I'm receiving the error message

1
  • I think if and the equals sign should switch positions​ Commented Mar 30, 2017 at 7:22

1 Answer 1

1

You swapped = and if in the definition of fix_error.

The syntax for a definition is:

name args = body

The syntax for an if expression is:

if condition then true_branch else false_branch

You simply need to combine these:

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

Or use a guard:

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

I’ve omitted the curly braces and semicolons, but you can include them if you prefer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.