How to parse an optional flag as a Maybe value?

ε祈祈猫儿з 提交于 2019-12-03 05:36:01

See the following passage of the optparse-applicative README:

Parsers are instances of both Applicative and Alternative, and work with any generic combinator, like many and some. For example, to make a option return Nothing instead of failing when it's not supplied, you can use the optional combinator in Control.Applicative:

optional $ strOption
   ( long "output"
  <> metavar "DIRECTORY" )

Accordingly, all you have to do is apply the optional combinator to the result of strOption:

import Options.Applicative

data Config = Config
    { cIn  :: Maybe String
    , cOut :: Maybe String
    } deriving Show

configParser :: Parser Config
configParser = Config
    <$> (optional $ strOption $ long "in" <> short 'i')
    <*> (optional $ strOption $ long "out" <> short 'o')

main :: IO ()
main = do
    conf <- execParser (info configParser fullDesc)
    print conf

Tests at the command line:

$ main --in foo -o bar
Config {cIn = Just "foo", cOut = Just "bar"}
$ main -i foo
Config {cIn = Just "foo", cOut = Nothing}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!