optparse-applicative defines command-line parsers declaratively in Haskell. A parser describes the values an application needs, then parses CLI input, validates required arguments and types, and generates help text. It replaces hand-written argument parsing when configuration must reach an application cleanly. section 15.3 section 15.3.1
Build a value parser with Parser and applicative composition. Each field gets a focused parser: strOption accepts unquoted strings, option auto parses types with Read instances, switch produces a Boolean flag, and optional wraps a parser in Maybe. long and short name an option; metavar and help document it. These option descriptions combine with (<>). section 15.3.1
Listing 15.13 An example of an argument parser
import Options.Applicative
...
argsParser :: Parser Args
argsParser = Args <$> strArg <*> intArg <*>
boolArg <*> maybeArg #1
where
strArg = #2
strOption $
long "string"
<> short 's'
<> metavar "STRING"
<> help "An example string"
intArg = #3
option auto $
long "integer"
<> short 'i'
<> metavar "INTEGER"
<> help "An example integer"
boolArg = #4
switch $
long "boolean"
<> short 'b'
<> help "An example boolean switch"
maybeArg = #5
optional $
strOption $
long "optional"
<> short 'o'
<> metavar "OPTIONAL"
<> help "An example optional string"
This parser assembles an Args record from required string and integer options, a Boolean switch, and an optional string. It also attaches short names, long names, metavariables, and help text to each option. section 15.3.1
Wrap the Parser in ParserInfo with info to add a full description, program description, header, and footer. Combining the parser with helper adds help handling; simpleVersioner adds version handling. Execute the result with execParser in main. Missing required options produce a usage error, while --help renders the generated option documentation. section 15.3.1
A configurable command
An Args value can require --string/-s and --integer/-i, while --boolean/-b defaults to False and --optional/-o becomes Nothing when omitted. Running with -s "Foo" -i 10 -b -o "Bar" produces a record whose flag is True and optional field is Just "Bar". Option order does not matter. section 15.3.1
For a file-synchronization application, the parsed CLI configuration is supplied to runApp alongside mainApp. This keeps command-line concerns at the application boundary while the application reads its configuration from its environment. section 15.2 section 15.3
