在Haskell中,有没有办法在函数保护中执行IO?

me2*_*me2 3 io haskell guard

例如:

newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
          | doesFileExist x == True = return False
          | otherwise = return True
Run Code Online (Sandbox Code Playgroud)

这可以使用吗?

Gre*_*con 18

你已经在IOmonad,所以为什么不使用以下?

newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
          | otherwise = do exists <- doesFileExist x
                           return $ not exists
Run Code Online (Sandbox Code Playgroud)

对于应用的善良:

import Control.Applicative

newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
          | otherwise = not <$> doesFileExist x
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,应用路线比您在问题中使用的警卫更简洁!


GS *_*ica 6

不,没有办法做到这一点(缺少不安全的技巧,这在这里是完全不合适的).

BTW doesFileExist x == True会更好地写doesFileExist x出来.


me2*_*me2 5

这有效并且可以满足需要:

newfile :: FilePath -> IO Bool
newfile fn = do 
    x <- runErrorT $ do
        when ((length fn) <= 0) (throwError "Empty filename")
        dfe <- liftIO $ doesFileExist fn
        when (dfe) (throwError "File already exists")
        return True
    return $ either (\_ -> False) id x
Run Code Online (Sandbox Code Playgroud)