如何将可选标志解析为 Maybe 值?

How to parse an optional flag as a Maybe value?

我正在尝试使用 optparse-applicative 来解析 Maybe String,但我无法在任何地方找到如何处理 Maybe。我发现的唯一一件事是添加一个默认值,但如果用户没有提供选项而不是 "",我真的需要一个 Nothing。有什么办法可以做到这一点吗?

这里是一个工作代码的例子:

import Options.Applicative

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

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


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

但是,我希望参数是可选的,并在 Config 中使用 Maybe String 而不是 String :

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

请看下面这段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" )

因此,您所要做的就是将 optional 组合子应用于 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

命令行测试:

$ main --in foo -o bar
Config {cIn = Just "foo", cOut = Just "bar"}
$ main -i foo
Config {cIn = Just "foo", cOut = Nothing}