optparse-appative回溯 [英] optparse-applicative Backtracking
问题描述
我正在尝试使用 optparse-applicative 库一个程序,它应该根据参数的数量执行不同的操作。
例如,计算周界的程序的参数解析:
module TestOpts其中
导入选项。应用程序
类型长度=双
数据PerimeterCommand
= GeneralQuadranglePerimeter长度长度长度
| RectanglePerimeter长度长度
parsePerimeterCommand :: Parser PerimeterCommand
parsePerimeterCommand = parseQuadPerimeter< |> parseRectPerimeter
parseQuadPerimeter = GeneralQuadranglePerimeter< $>
parseLengthSIDE1< *>
parseLengthSIDE2< *>
parseLengthSIDE3< *>
parseLengthSIDE4
parseRectPerimeter = RectanglePerimeter< $>
parseLengthWIDTH< *> parseLengthHEIGHT
parseLength name = argument auto(metavar name)
只有< |>
的第一个参数才能成功解析。我认为需要某种参数回溯,类似于Parsec的 try
combinator。
关于如何解析可选择的参数集合,当第一个选择可能会消耗一些下一个选择的参数? 解决方案
请注意:this答案是由optparse-applicative作者Paolo Capriotti撰写的。
你无法直接使用optparse-applicative来做这件事。 optparse-appative的主要功能
是可以按任意顺序解析选项。如果
想要主要使用参数(它是位置型的),则有
有两级解析器会更好:在$中使用多个参数
b $ b optparse-applicative,然后将结果数组传递给一个普通的解析器
(比如使用Parsec)。如果你只有 有位置参数,那么
optparse-applicative不会给你很多钱,你可以用Parsec手动解析
参数。
I'm trying to use the optparse-applicative library in an program which should perform a different action depending on the number of arguments.
For example, the argument parsing for a program which calculates perimeters:
module TestOpts where
import Options.Applicative
type Length = Double
data PerimeterCommand
= GeneralQuadranglePerimeter Length Length Length Length
| RectanglePerimeter Length Length
parsePerimeterCommand :: Parser PerimeterCommand
parsePerimeterCommand = parseQuadPerimeter <|> parseRectPerimeter
parseQuadPerimeter = GeneralQuadranglePerimeter <$>
parseLength "SIDE1" <*>
parseLength "SIDE2" <*>
parseLength "SIDE3" <*>
parseLength "SIDE4"
parseRectPerimeter = RectanglePerimeter <$>
parseLength "WIDTH" <*> parseLength "HEIGHT"
parseLength name = argument auto (metavar name)
Only the first argument to <|>
will ever successfully parse. I think some kind of argument backtracking is required, similar to Parsec's try
combinator.
Any ideas on how to parse alternative sets of arguments, when the first alternative may consume some arguments of the next alternative?
Please note: this answer was written by the optparse-applicative author, Paolo Capriotti.
You can't do this with optparse-applicative directly. The main feature
of optparse-applicative is that options can be parsed in any order. If
you want to work mainly with arguments (which are positional), you are
better off having two levels of parsers: use many argument
in
optparse-applicative, then pass the resulting array to a normal parser
(say using Parsec). If you only have positional arguments, then
optparse-applicative won't buy you very much, and you could just parse
the arguments manually with Parsec.
这篇关于optparse-appative回溯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!