[Haskell-cafe] Using catch and errors

Alexandre Weffort Thenorio alethenorio at home.se
Fri Apr 22 12:14:09 EDT 2005

Thanks for the tips.

>(There's also the obvious syntax error of not quoting the string
>"int.hex", but I suspect you would have caught that one.)

In fact it was supposed to be there. Just a typo I guess

>After the catch, you have another instance of the readFile command you
>would have just run, which you probably don't want.

Typo :)

>It's important that getLine is aligned with putStrLn and the rest of
>the do block, if you use something like the emacs haskell-mode, you
>can have your editor align this automatically, or semi-automatically
>for you.

Sure did the trick by aligning it.

Well after getting all the tips from you and the other answers I came up
with a working version below:

main :: IO()
main =do
  ex <- doesFileExist "./newint.hex"
  when ex (catch (removeFile "./newint.hex") (\_ -> do putStrLn "Not
possible to remove newint.hex, Please close all programs using this
file.\nPress RETURN (ENTER) to quit."
              exitWith ExitSuccess))
  hexFile <- catch (readFile "int.hex") (\_ -> do putStrLn "File int.hex not
found.\nPress RETURN (ENTER) to quit."
         exitWith ExitSuccess)
  putStr "What is the key number (0 or 1)?\n"
  keyno <- getLine
  when ((length keyno /= 1) && (keyno /= "1") && (keyno /= "0")) (error
"Please input either 0 or 1 as key number")
  putStr "Input key.\n"
  key <- getLine

  newLine <- outputLine keyno key (lines(hexFile))
  putStrLn ("newint.hex created with key " ++ key ++ ". Press RETURN (Enter)
to quit")

Now I have one problem (Well 2 really but the second one is just me not
having programmed in haskell for so long that I forgot). getLine is used for
the sole purpous of stopping the program and allowing the user to read the
error message before the window closes but error does not allow me to do
that and aparently using a lambda function (As shown below) does not work
(It gives error upon compilation

 when ((length keyno /= 1) && (keyno /= "1") && (keyno /= "0")) (\_ ->
putStrLn "Please input either 0 or 1 as key number"


exitWith ExitSuccess)

So is there anyway to fix that?

The second error is that apparenlty (keyno /= "1") and (keyno /= "0") do not
work, but I suspect that, like Java, one can't compare strings using = sign
or am I wrong?

>Check out the wiki:
>-- lots of beginner questions and answers have been accumulated there.

>Also, to really understand what's going on with the do-notation, it
>would be best that you learn what monads are about. I'll direct you at
>the "All About Monads" tutorial:
>And of course, my own take on them:  :)

Mostly appreciated

>Hope this helps,

Surelly did. Don't know what I would do without you guys.

 Best Regards


More information about the Haskell-Cafe mailing list