Я пытаюсь создать небольшую программу в Haskell в Лексах, которая преобразует файл .lhs в файл .hs. Но я не могу заставить его строить без ошибок. Любая помощь будет оценена по достоинству. Я новичок в Haskell, поэтому простите меня, если ответ очевиден, хотя я не вижу его. Вот код, и сообщение об ошибке:Как использовать catch с ручкой IO
-- Converts .lhs (literary Haskell files) to .hs (plain Haskell files)
-- Keeps only the statements which are normally compiled, plus blank lines.
-- To use:
-- ghc --make lhs2hs.hs
-- to get an executable file lhs2hs.
-- Then
-- lhs2hs filename
-- will open filename.lhs and save the converted file in filename.hs
-- by Scot Drysdale on 7/28/07, based on SOE program on p. 241
module Main where
import System.IO
-- import System.IO.Error (catchIOError)
import Control.Exception (catch)
import System.Environment -- to allow getArgs
-- Opens a file, given name and mode
openGivenFile :: String -> IOMode -> IO Handle
openGivenFile name mode
= catch (do handle <- openFile name mode
return handle)
handler
where
handler :: IOError -> IO Handle
-- Next line does not match IO Handle
handler ex = putStrLn $ "Caught exception: " ++ show ex
-- (\e -> error ("Cannot open " ++ name))
main = do args <- getArgs
fromHandle <- openGivenFile (args !! 0 ++ ".lhs") ReadMode
toHandle <- openGivenFile (args !! 0 ++ ".hs") WriteMode
convertFile fromHandle toHandle
hClose fromHandle
hClose toHandle
-- Converts all the lines in a file
convertFile :: Handle -> Handle -> IO()
convertFile fromHandle toHandle
= catch (do line <- hGetLine fromHandle
case line of
('>' : ' ' : rest) -> hPutStrLn toHandle rest
('>' : rest) -> hPutStrLn toHandle rest
('\n' : rest) -> hPutStrLn toHandle line
('\r' : rest) -> hPutStrLn toHandle line
_ -> return()
convertFile fromHandle toHandle)
handler
where
handler :: IOError -> IO()
handler ex = putStrLn $ "Caught exception: " ++ show ex
Ошибка:
src\Main.hs:27:28-69:
Couldn't match type `()' with `Handle'
Expected type: IO Handle
Actual type: IO()
In the expression: putStrLn $ "Caught exception: " ++ show ex
In an equation for `handler':
handler ex = putStrLn $ "Caught exception: " ++ show ex
In an equation for `openGivenFile':
openGivenFile name mode
= catch
(do { handle <- openFile name mode;
return handle })
handler
where
handler :: IOError -> IO Handle
handler ex = putStrLn $ "Caught exception: " ++ show ex
'putStrLn' возвращает' IO() '. Я не знаю, почему вы ожидаете, что это сработает. Если вы ожидаете возможности отказа, возвращайте 'IO (Maybe Handle)' - добавьте 'Just' к основному пути и' return Nothing' вашему обработчику –
Спасибо. Я знал, что это был ИО, но я не знал, как его адресовать. Еще раз спасибо. – te7