gpt4 book ai didi

haskell - 如何在数据构造函数内将 Int 与 optparse-applicative 一起使用?

转载 作者:行者123 更新时间:2023-12-02 12:37:58 26 4
gpt4 key购买 nike

我想使用 optparse-applicative包将命令行参数添加到我的程序中。

程序需要不同类型的参数(StringInt)。为了简单起见,我希望只有一种数据类型来保存我的所有设置,如下所示:

data Configuration = Configuration
{ foo :: String
, bar :: Int
}

我找到了一种方法 here去做这个。但不幸的是,功能似乎已经改变了。

这是我想做的一个最小的(不是)工作示例:

module Main where

import Options.Applicative
import Control.Monad.Trans.Reader

data Configuration = Configuration
{ foo :: String
, bar :: Int
}

configuration :: Parser Configuration
configuration = Configuration
<$> strOption
( long "foo"
<> metavar "ARG1"
)
<*> option
( long "bar"
<> metavar "ARG2"
)

main :: IO ()
main = do
config <- execParser (info configuration fullDesc)
putStrLn (show (bar config) ++ foo config)

有没有一种简单的方法可以做到这一点,或者我是否必须实现类似于 strOptionintOption

最佳答案

您需要做的就是告诉选项使用自动阅读器,如以下代码片段所示:

configuration :: Parser Configuration
configuration = Configuration
<$> strOption
( long "foo"
<> metavar "ARG1"
)
<*> option auto
( long "bar"
<> metavar "ARG2"
)

strOption 和 option 之间的区别在于 strOption 假定 String 返回类型,而 option 可以配置为使用自定义读取器。 auto 读取器假定返回类型为 Read 实例。

OptParse applicative中有很好的文档黑客页面。

我希望这会有所帮助。

关于haskell - 如何在数据构造函数内将 Int 与 optparse-applicative 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com