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
caseexpression: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
readslike this is perfectly acceptable; it’s basically the only way to recover properly from invalid reads, at least until we getreadMaybeor 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 acaseexpression is less acceptable 🙂Another possible alternative, using the view patterns extension, is
This avoids the one-use
aIntegerbinding, 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
baselibrary, 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).