在Haskell中报告锁定文件的更好方法

时间:2017-04-19 14:29:10

标签: haskell exception-handling maybe

我想在Haskell中锁定一个专用文件,并在已经锁定的情况下抛出IOError

import Data.Maybe (fromMaybe)
import System.FileLock (FileLock, SharedExclusive (Exclusive), tryLockFile)

-- ...
do
  -- ...
  maybeFileLock <- tryLockFile path Exclusive -- returns Maybe FileLock
  let fileLock = fromMaybe (throwIO (userError "File locked")) maybeFileLock

有没有更好的方法来处理Maybe,如果是Nothing则只抛出异常?我可以将这两行合并为一个吗?

N.B。:有人可能会争辩说,这些行的任何组合都会使意图不那么明确。

1 个答案:

答案 0 :(得分:3)

fileLock <- fromMaybe (throwIO (userError "File locked"))
  <$> tryLockFile path Exclusive

但是throwIO :: Exception e => e -> IO a,因此这个和您的代码在FileLockIO a之间应该不匹配。代替:

fileLock <- maybe (throwIO (userError "File locked")) pure
  =<< tryLockFile path Exclusive