Éowyn
Éowyn

Reputation: 187

parse error on input `if' in catch clause for readFile

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

Upvotes: 0

Views: 81

Answers (1)

Jon Purdy
Jon Purdy

Reputation: 54999

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.

Upvotes: 1

Related Questions