Idiomatic way to conditionally handle IO in Haskell

I am writing a small shell script in Haskell that can take an optional argument. However, if there is no argument, I would like to get a string from stdin in which the value is requested.

What would be the idiomatic way to do this in Haskell?

#!/usr/bin/env runhaskell import Control.Applicative ((<$>)) import Data.Char (toLower) import IO (hFlush, stdout) import System.Environment (getArgs) main :: IO () main = do args <- getArgs -- here should be some sort of branching logic that reads -- the prompt unless `length args == 1` name <- lowerCase <$> readPrompt "Gimme arg: " putStrLn name lowerCase = map toLower flushString :: String -> IO () flushString s = putStr s >> hFlush stdout readPrompt :: String -> IO String readPrompt prompt = flushString prompt >> getLine 

Oh, and if there is a way to do this with something from Control.Applicative or Control.Arrow , I would like to know. I was very interested in these two modules.

Thanks!

+7
source share
2 answers
 main :: IO () main = do args <- getArgs name <- lowerCase <$> case args of [arg] -> return arg _ -> readPrompt "Gimme arg: " putStrLn name 
+8
source

This does not match your specific use case, but the question title made me immediately think when from Control.Monad . Straight from the docs :

when :: Monad m => Bool -> m () -> m ()

Conditional execution of monadic expressions.

Example:

 main = do args <- getArgs -- arg <- something like what FUZxxl did.. when (length args == 1) (putStrLn $ "Using command line arg: " ++ arg) -- continue using arg... 

You can also use when cousin unless .

+1
source

All Articles