如何将可选标志解析为Maybe值? [英] How to parse an optional flag as a Maybe value?

查看:85
本文介绍了如何将可选标志解析为Maybe值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 optparse-applicative 来解析也许是字符串,但是我在任何地方都找不到如何处理也许的方法。我发现的唯一一件事就是添加一个默认值,但是如果用户没有提供选项而不是 ,我真的需要 Nothing code>。有什么方法可以实现?

I'm trying to use optparse-applicative to parse a Maybe String but I can't find anywhere how to deal with Maybe. The only thing I found is to add a default value but I really need a Nothing if user didn't supply an option instead of "". Is there any way to achieve this ?

以下是工作代码示例:

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 中使用也许是字符串代替 String

However, I would like the parameters to be optional and use Maybe String instead of String in Config :

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


推荐答案

请参见以下 optparse-applicative 自述文件

See the following passage of the optparse-applicative README:


解析器是 Applicative 替代,并与任何通用组合器(例如很多 some >。例如,要使
a选项返回 Nothing 而不是在未提供时失败,则
可以使用可选 Control.Applicative 中的code>组合器:

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" )


相应地,您要做的就是将可选组合器应用于 strOption

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

在命令行中进行测试:

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

这篇关于如何将可选标志解析为Maybe值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆