如何在Haskell中对函数中的真/假进行模式匹配?

yuvru6vn  于 2022-11-14  发布在  其他
关注(0)|答案(2)|浏览(200)

我尝试手动处理文件错误,以便打印我自己的消息,目前我有以下代码:

  1. handleFileError :: FileError -> IO a
  2. handleFileError (FileError errorKind) = do
  3. case errorKind of
  4. NotFound -> undefined
  5. NoPermission -> undefined
  6. IsDirectory -> undefined
  7. fileRead :: String -> IO String
  8. fileRead file = do
  9. pathExists <- doesPathExist file
  10. notDirectory <- doesFileExist file
  11. -- These two must be handled before `System.Directory.getPermissions` is called
  12. -- or else it will error.
  13. permissions <- getPermissions file
  14. let hasReadPermissions = readable permissions
  15. if hasReadPermissions then undefined -- This is the success case
  16. else handleFileError $ FileError NoPermissions

我想检查3个布尔值(pathExists,notDirectory和hasReadPermissions)中是否有一个为false,然后相应地执行。我尝试使用False的case来实现这一点,但是这总是运行第一个分支。

o2g1uqev

o2g1uqev1#

一种方法是使用MultiWayIf

  1. do
  2. pathExists <- doesPathExist file
  3. notDirectory <- doesFileExist file
  4. permissions <- unsafeInterleaveIO (getPermissions file)
  5. if
  6. | not pathExists -> -- ...
  7. | not notDirectory -> -- ...
  8. | not permissions -> -- ...
  9. | otherwise -> -- ...

如果您对扩展过敏,则获得此功能的老式方法是使用guards,如下所示:

  1. case () of
  2. _ | not pathExists -> -- ...
  3. | not notDirectory -> -- ...
  4. | not permissions -> -- ...
  5. | otherwise -> -- ...

但是我不推荐这两种方法,相反,只要对文件做些什么,然后捕获异常;否则,在检查和文件使用之间,文件系统会发生变化,出现竞争情况。

  1. fileRead :: String -> IO String
  2. fileRead = catch (undefined {- success case -}) $ \e -> if
  3. | isDoesNotExistError e -> -- ...
  4. | isPermissionError e -> -- ...
  5. | otherwise -> throw e
展开查看全部
i2byvkas

i2byvkas2#

我已经解决了这个问题--我没有意识到嵌套if语句的方式可以像其他语言中的else-if一样:

  1. if not (pathExists) then handleFileError $ FileError NotFound
  2. else if not (notDirectory) then handleFileError $ FileError IsDirectory
  3. else do
  4. permissions <- getPermissions file
  5. let hasReadPermissions = readable permissions
  6. if hasReadPermissions then undefined -- success
  7. else handleFileERror $ FileError NoPermissions

相关问题