例えば:
newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
| doesFileExist x == True = return False
| otherwise = return True
これを機能させることはできますか?
あなたはすでにIO
モナドにいるので、なぜ以下を使用しませんか?
newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
| otherwise = do exists <- doesFileExist x
return $ not exists
適用の良さのために:
import Control.Applicative
newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
| otherwise = not <$> doesFileExist x
ご覧のとおり、適用ルートは、質問で使用したい警備員よりもさらに簡潔です。
いいえ、これを行う方法はありません(ここでは完全に不適切な安全でないトリックがない限り)。
ところで、それが可能だったdoesFileExist x == True
ので、もっとよく書かれるでしょう。doesFileExist x
これは機能し、必要なことを実行します。
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
ガード句のタイプはである必要がありますBool
。のタイプはdoesFileExist x
ですIO Bool
。タイプの不一致は、それができないことを意味します。