haskellio

Haskell saferead of file


I am attempting to write a simple Haskell function that reads a files contents, if the file exists, and does nothing otherwise.

safeRead :: String -> IO ()
safeRead path = readFile path `catch` handleExists
  where handleExists e
    | isDoesNotExistError e = return ()
    | otherwise = throwIO e

This, however, fails with: parse error (possibly incorrect indentation or mismatched brackets)

Why? I've double checked the indentation several times and all seems fine by me?


Solution

  • You have two errors.

    One, as Daniel Sanchez pointed out, is that you're missing an = after otherwise.

    The other is that the cases of handleExists must be indented more than the function name, not the where. In other words, move the two | to the right beyond the h of handleExists.