
On 4/22/05, Alexandre Weffort Thenorio
I am trying to get catch to work but I guess I am total newbie on this one.
main :: IO() main = do removeFile "./newint.hex" hexFile <- catch (readFile int.hex) (\_ -> do putStrLn "Cannot find int.hex" getLine --Simply stop program so user can read error message return() --Quit) hexFile <- readFile "int.hex" --res of program goes here getLine return()
But it keeps giving me error on getLine. How can I quit a program in case of an error giving an error message?
Try: main :: IO () main = do removeFile "./newint.hex" hexFile <- catch (readFile "int.hex") (\_ -> error "Cannot find int.hex") getLine return () Notice that 'return' in Haskell is very different from 'return' in C.
Also I tried something like
main :: IO() main = do ex <- doesFileExist "./newint.hex" if ex then removeFile "./newint.hex"
But that won't work either. Any ideas? I'd like to catch different errors and quit program giving different error messages
'if/then/else' expressions _must_ have an 'else' part. In this case you can use 'Control.Monad.when': 'when ex (removeFile "newint.hex")'.
Last but not least I have the function
outputLine keyno key orgFile = do let part1 = getLeft keyno (orgFile!!1) let part2 = getRight keyno (orgFile!!1) let total = part1 ++ (map toUpper key) ++ part2 let checks = checksum (drop 1 total) let final = total ++ checks ++ "\n" newHexFile <- openFile "newint.hex" WriteMode hPutStrLn newHexFile (orgFile!!0 ++ "\n" ++ final ++ unlines (drop 2 orgFile))
I'd like to be able to check for stuff such as size of key and wheter keyno is only 1 or 0 and quit program with error message otherwise but again couldn't quite get catch to work.
You can use pattern matches and guards for that. outputLine keyno key (orgFile1:orgFile2:restOfOrgFile) | length key == someKeyLength = your code here | otherwise = error "Invalid key length" outputLine keyno key orgFile = error "invalid orgFile" I'm not sure what you use 'keyno' for but perhaps you could define a 'data Keyno = Zero | One' data type and catch such errors at compile-time?
Any reading tips about subject would be appreciated.
I've heard "Yet Another Haskell Tutorial" should be good but I've never read it myself. You can download it from http://www.isi.edu/~hdaume/htut/ -- Friendly, Lemmih