This more of a style question, rather than a how to.
So I've got a program that needs two command line arguments: a string and an integer.
I implemented it this way:
main = do args@(~( aString : aInteger : [] ) ) <- getArgs let parsed@( ~[(n,_)] ) = reads aInteger if length args /= 2 || L.null parsed then do name <- getProgName hPutStrLn stderr $ "usage: " ++ name ++ " <string> <integer>" exitFailure else do doStuffWith aString n
While this works, this is the first time I've really used command line args in Haskell, so I'm not sure whether this is a horribly awkward and unreadable way to do what I want.
Using lazy pattern matching works, but I could see how it could be frowned upon by other coders. And the use of reads to see if I got a successful parse definitely felt awkward when writing it.
Is there a more idiomatic way to do this?
I suggest using a case
expression:
main :: IO () main = do args <- getArgs case args of [aString, aInteger] | [(n,_)] <- reads aInteger -> doStuffWith aString n _ -> do name <- getProgName hPutStrLn stderr $ "usage: " ++ name ++ " <string> <integer>" exitFailure
The binding in a guard used here is a pattern guard, a new feature added in Haskell 2010 (and a commonly-used GHC extension before that).
Using reads
like this is perfectly acceptable; it's basically the only way to recover properly from invalid reads, at least until we get readMaybe
or something of its ilk in the standard library (there have been proposals to do it over the years, but they've fallen prey to bikeshedding). Using lazy pattern matching and conditionals to emulate a case
expression is less acceptable :)
Another possible alternative, using the view patterns extension, is
case args of [aString, reads -> [(n,_)]] -> doStuffWith aString n _ -> ...
This avoids the one-use aInteger
binding, and keeps the "parsing logic" close to the structure of the argument list. However, it's not standard Haskell (although the extension is by no means controversial).
For more complex argument handling, you might want to look into a specialised module — System.Console.GetOpt is in the standard base
library, but only handles options (not argument parsing), while cmdlib and cmdargs are more "full-stack" solutions (although I caution you to avoid the "Implicit" mode of cmdargs, as it's a gross impure hack to make the syntax a bit nicer; the "Explicit" mode should be just fine, however).
I agree the optparse-applicative
package is very nice. Awesome! Let me give an up-to-date example.
The program takes as arguments a string and an integer n, returns the string replicated n times, and it has a flag which reverses the string.
-- file: repstring.hs import Options.Applicative import Data.Monoid ((<>)) data Sample = Sample { string :: String , n :: Int , flip :: Bool } replicateString :: Sample -> IO () replicateString (Sample string n flip) = do if not flip then putStrLn repstring else putStrLn $ reverse repstring where repstring = foldr (++) "" $ replicate n string sample :: Parser Sample sample = Sample <$> argument str ( metavar "STRING" <> help "String to replicate" ) <*> argument auto ( metavar "INTEGER" <> help "Number of replicates" ) <*> switch ( long "flip" <> short 'f' <> help "Whether to reverse the string" ) main :: IO () main = execParser opts >>= replicateString where opts = info (helper <*> sample) ( fullDesc <> progDesc "Replicate a string" <> header "repstring - an example of the optparse-applicative package" )
Once the file is compiled (with ghc
as usual):
$ ./repstring --help repstring - an example of the optparse-applicative package Usage: repstring STRING INTEGER [-f|--flip] Replicate a string Available options: -h,--help Show this help text STRING String to replicate INTEGER Number of replicates -f,--flip Whether to reverse the string $ ./repstring "hi" 3 hihihi $ ./repstring "hi" 3 -f ihihih
Now, assume you want an optional argument, a name to append at the end of the string:
-- file: repstring2.hs import Options.Applicative import Data.Monoid ((<>)) import Data.Maybe (fromJust, isJust) data Sample = Sample { string :: String , n :: Int , flip :: Bool , name :: Maybe String } replicateString :: Sample -> IO () replicateString (Sample string n flip maybeName) = do if not flip then putStrLn $ repstring ++ name else putStrLn $ reverse repstring ++ name where repstring = foldr (++) "" $ replicate n string name = if isJust maybeName then fromJust maybeName else "" sample :: Parser Sample sample = Sample <$> argument str ( metavar "STRING" <> help "String to replicate" ) <*> argument auto ( metavar "INTEGER" <> help "Number of replicates" ) <*> switch ( long "flip" <> short 'f' <> help "Whether to reverse the string" ) <*> ( optional $ strOption ( metavar "NAME" <> long "append" <> short 'a' <> help "Append name" ))
Compile and have fun:
$ ./repstring2 "hi" 3 -f -a rampion ihihihrampion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With