简体   繁体   English

optparse适用的回溯

[英]optparse-applicative Backtracking

I'm trying to use the optparse-applicative library in an program which should perform a different action depending on the number of arguments. 我正在尝试在程序中使用optparse-applicative库,该库应根据参数数量执行不同的操作。

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. 我认为需要某种形式的参数回溯,类似于Parsec的try组合器。

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. 请注意:此答案是由适用于optparse的作者Paolo Capriotti撰写的。

You can't do this with optparse-applicative directly. 您不能直接使用optparse-applicative进行此操作。 The main feature of optparse-applicative is that options can be parsed in any order. optparse-applicative的主要功能是可以按任何顺序解析选项。 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). 如果要主要使用参数(位置参数),则最好具有两个层次的解析器:在optparse-applicative中使用many argument ,然后将结果数组传递给常规解析器(例如使用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-applicative不会给您带来多少好处,您可以使用Parsec手动解析参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM