我試圖寫一個簡單的函數來安全地讀取一個文件(如果存在),什麼也不做,如果該文件不存在:哈斯克爾安全IO
safeRead :: String -> IO()
safeRead path = readFile path `catch` handleExists
where handleExists e
| isDoesNotExistError e = return()
| otherwise = throwIO e
這種失敗在編譯時有
Couldn't match type ‘[Char]’ with ‘()’
Expected type: IO()
Actual type: IO String
In the first argument of ‘catch’, namely ‘readFile path’
In the expression: readFile path `catch` handleExists
這是有道理的,因爲:t readFile
是readFile :: FilePath -> IO String
。例如,返回IO String
(和IO String
是不一樣的IO()
)
更改簽名String -> IO String
Couldn't match type ‘()’ with ‘[Char]’
Expected type: IOError -> IO String
Actual type: IOError -> IO()
In the second argument of ‘catch’, namely ‘handleExists’
In the expression: readFile path `catch` handleExists
這也使得自handleExists的類型爲IO()
爲了節省大家的查找意義上的功能,漁具是用進口的: import Control.Exception
漁獲簽名是: catch :: Exception e => IO a -> (e -> IO a) -> IO a
我真正的問題是,我如何在Haskell中編寫這種錯誤安全,靈活的代碼?更具體地說,我將不得不對這個函數做出什麼改變,使它能夠處理成功案例和失敗案例?
您的代碼爲我編譯使'isDoesNotexistError'總是返回true,所以問題可能在其他部分? – Netwave
是的,剛纔檢查,throwIO是返回一個'IO了','不IO()' – Netwave
對我來說,似乎你正在尋找的簽名是'字符串 - > IO(也許字符串)' – Carsten