sevo
sevo

Reputation: 4609

Simplest way to mix anonymous conditions with IO

How to avoid boilerplate assignments like doesExist <- doesDirectoryExist path and case doesExist of ... within IO?

Is there a more idiomatic way than this?

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

Upvotes: 1

Views: 54

Answers (2)

Izabel
Izabel

Reputation: 191

Or same with "if":

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

Upvotes: 0

Andr&#225;s Kov&#225;cs
Andr&#225;s Kov&#225;cs

Reputation: 30103

LambdaCase is applicable here:

{-# LANGUAGE LambdaCase #-}

import System.Directory
import System.Environment

main = do
  path:_ <- getArgs    

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

Upvotes: 2

Related Questions