如何用optparse-appative来解析 [英] How to parse Maybe with optparse-applicative
问题描述
我正尝试使用 optparse-applicative 来解析可能是String
但我无法找到任何地方如何处理也许
。我唯一发现的是添加一个默认值,但如果用户没有提供一个选项而不是 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 ?
这是一个工作代码的例子:
Here is an example of working code:
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
而不是字符串
> p>
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
README a>:
See the following passage of the optparse-applicative
README:
解析器是
Applicative
和Alternative
,并使用任何通用组合器工作
,如许多
和某些
。例如,要使
a选项返回Nothing
,而不是在未提供时失败,那么
可以使用可选的 code> Combinator in
Control.Applicative
:
Parsers are instances of both
Applicative
andAlternative
, and work with any generic combinator, likemany
andsome
. For example, to make a option returnNothing
instead of failing when it's not supplied, you can use theoptional
combinator inControl.Applicative
:
optional $ strOption
( long "output"
<> metavar "DIRECTORY" )
因此,您只需将可选的
组合子应用于 strOption $ c的结果$ c $:
$ b
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}
这篇关于如何用optparse-appative来解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!