Haskell,optparse-generic 的未命名命令行参数
Haskell, unnamed command line arguments for optparse-generic
我正在使用 optparse-generic 来解析名为 example
的程序的命令行参数。我有一个带有命名字段的数据类型(记录语法)。例如:
data Example = Example { foo :: Int, bar :: String } deriving (Generic, Show)
这将生成一个可以按如下方式调用的程序:
./example --foo 42 --bar "baz"
我如何告诉 optparse-generic bar
应该是一个未命名的、强制的、位置命令行参数。这意味着,我不想在调用 example
时键入 --bar
。例如,我想调用 example
如下:
./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
我正在使用 optparse-generic 来解析名为 example
的程序的命令行参数。我有一个带有命名字段的数据类型(记录语法)。例如:
data Example = Example { foo :: Int, bar :: String } deriving (Generic, Show)
这将生成一个可以按如下方式调用的程序:
./example --foo 42 --bar "baz"
我如何告诉 optparse-generic bar
应该是一个未命名的、强制的、位置命令行参数。这意味着,我不想在调用 example
时键入 --bar
。例如,我想调用 example
如下:
./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