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

Better way to report locked file in Haskell

我想在 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.:有人可能会争辩说,这些行的任何组合都会使意图不那么清晰。

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