Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - readFile catch exception

I am trying to read file in Haskell with exception catching but cant get working. The code looks like:

     module Main where
    import System.Environment
    import System.IO
    import System.Exit

    main = do
        x:xs <- getArgs
        case length(x:xs) of
            2 -> do catch (readFile x)
                        (\_ -> do   putStrLn ("Error on reading file: " ++ x) 
                                    getLine
                                    exitWith ExitSuccess)
            _ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>
                exitFailure

And I get this error:

Couldn't match expected type `IO String
                              -> (ExitCode -> IO a)
                              -> ExitCode
                              -> IO String'
       against inferred type `IO ()'
In the expression:
    putStrLn
      ("Error on reading file: " ++ x) getLine exitWith ExitSuccess
In the expression:
    do { putStrLn
           ("Error on reading file: " ++ x) getLine exitWith ExitSuccess }
In the second argument of `catch', namely
    `(\ _ -> do { putStrLn
                    ("Error on reading file: " ++ x) getLine exitWith ExitSuccess })'

Can you give me a hint? Thanks

like image 682
Martin Pilch Avatar asked Jun 25 '26 12:06

Martin Pilch


1 Answers

You have an extra >> (or an extra do) on line 13:

_ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>

should be:

_ -> do putStrLn ("Run this way: ./projekt inputFile RE")

or:

_ -> putStrLn ("Run this way: ./projekt inputFile RE") >> exitFailure

Full code:

main = do
l@(x:xs) <- getArgs
case length l of
    2 -> do catch (readFile x) $ \_ -> do
            putStrLn $ "Error on reading file: " ++ x
            getLine
            exitWith ExitSuccess
    _ -> do putStrLn $ "Run this way: ./projekt inputFile RE"
            exitFailure
like image 171
Alvivi Avatar answered Jun 28 '26 18:06

Alvivi