Search code examples
haskellioguard

In Haskell, is there a way to do IO in a function guard?


For example:

newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
          | doesFileExist x == True = return False
          | otherwise = return True

Can this be made to work?


Solution

  • This works and does what's needed:

    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