将匿名条件与IO混合的最简单方法

时间:2015-02-14 13:00:33

标签: haskell

如何避免在IO中使用doesExist <- doesDirectoryExist pathcase doesExist of ...等样板分配?

是否有比这更惯用的方式?

import System.Directory
import System.Environment

main = do
  path:_ <- getArgs
  doesDirectoryExist path >>= cond
    (putStrLn $ path ++ " Exists")
    (putStrLn $ path ++ " Does not exist")

cond b c a = if a then b else c

2 个答案:

答案 0 :(得分:2)

LambdaCase适用于此处:

{-# LANGUAGE LambdaCase #-}

import System.Directory
import System.Environment

main = do
  path:_ <- getArgs    

  doesDirectoryExist path >>= \case
    True -> putStrLn $ path ++ " Exists"
    _    -> putStrLn $ path ++ " Does not exist"

答案 1 :(得分:0)

或者&#34;如果&#34;:

doesDirectoryExist path >>= \x ->
 if x then (putStrLn "Exists") else putStrLn ("Does not")