gpt4 book ai didi

Haskell,optparse-generic 的未命名命令行参数

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

我正在使用optparse-generic解析名为 example 的程序的命令行参数。我有一个带有命名字段的数据类型(记录语法)。例如:

data Example = Example { foo :: Int, bar :: String } deriving (Generic, Show)

这会生成一个可以按如下方式调用的程序:

./example --foo 42 --bar "baz"

我如何告诉 optparse-generic bar 应该是一个未命名的、强制的、位置命令行参数。这意味着,当我调用 example 时,我不想输入 --bar。例如,我想调用以下示例:

./example --foo 42 "baz"

最佳答案

optparse-generic 不支持从单个数据类型定义生成这样的解析器,因为 Haskell 不支持同时具有标记和未标记字段的记录。

但是,您可以做的是为所有标记字段生成一种数据类型,为未标记字段生成一种类型,然后使用 Applicative 操作将它们组合起来,如下所示:

data Labeled = Labeled { foo :: Int } deriving (Generic, Show)

instance ParseRecord Labeled

data Unlabeled = Unlabeled String deriving (Generic, Show)

instance ParseRecord Unlabeled

data Mixed = Mixed Labeled Unlabeled deriving (Show)

instance ParseRecord Mixed where
parseRecord = Mixed <$> parseRecord <*> parseRecord

关于Haskell,optparse-generic 的未命名命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375556/

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