本文介绍了Haskell,optparse-generic的无名命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用来解析程序的命令行参数称为示例。我有一个数据类型与命名字段(记录语法)。例如:

  data示例=示例{foo :: Int,bar :: String}派生(Generic,Show)

这会生成一个程序,可以这样调用:

  ./ example --foo 42 --barbaz

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

  ./示例--foo 42baz


解决方案

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


$ b $然而,你可以做的是为所有标记的字段生成一个数据类型,为未标记的字段生成一个数据类型,然后使用 Applicative 操作将它们合并,就像这样:

  data标记=标记{foo :: Int}派生(Generic,Show)

实例ParseRecord标记的

数据Unlabeled =未标记的字符串派生(通用,显示)

实例ParseRecord未标记的

数据混合=混合标记未标记的派生(显示)

实例ParseRecord混合其中
parseRecord =混合< $> parseRecord< *> parseRecord


I'm using optparse-generic to parse the command line arguments of a program called example. I have a datatype with named fields (record syntax). For example:

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

This generates a program which can be called as follows:

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

How can I tell optparse-generic that bar should be an unnamed, mandatory, positional command line argument. That means, I don't want to type --bar when I call example. For example, I want to call example the following:

./example --foo 42 "baz"
解决方案

optparse-generic does not support generating such a parser from a single data type definition since Haskell does not support records with both labeled and unlabeled fields.

However, what you can do is generate one data type for all the labeled fields and one type for the unlabeled fields and then combine them using Applicative operations, like this:

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的无名命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 18:13