【问题标题】:PetitParser: How to match to token setPetitParser:如何匹配令牌集
【发布时间】:2019-11-25 17:13:53
【问题描述】:

在 PetitParser2 中,我如何匹配一组封闭的标记,例如月份名称?例如。 (在伪代码中) [ :word | MonthNames anySatisfy: [ :mn | mn beginsWith: word ] ] asParser.

PPPredicateSequenceParser 似乎是一种可能,但您似乎必须提前知道字符串的大小。我想我可以这样做:

| monthRules |
    monthRules := Array streamContents: [ :unamused: |
        MonthNames collect: [ :e | 
            s nextPut: e asString asPParser.
            s nextPut: (e first: 3) asPParser ] ].
    ^ PP2ChoiceNode withAll: monthRules

但我想知道是否有内置/直截了当的东西

【问题讨论】:

    标签: smalltalk pharo petitparser


    【解决方案1】:

    其他更笨拙且效率更低的选择是使用自定义块:

    [ :context | 
        | position names |
        names := #('January' 'February' 'March' 'April').   
        position := context position.
        names do: [ :name | 
            (context next: name size) = name ifTrue: [  
                ^ name
            ] ifFalse: [ 
                context position: position
            ]
        ].
        ^ PP2Failure new
    ] asPParser parse: 'April'
    

    不过我不建议这样做,因为 PP2 对块一无所知,也无法应用任何优化。

    【讨论】:

      【解决方案2】:

      我建议对集合中的每个元素使用解析器:

      monthsParser := 'January' asPParser / 
                      'February' asPParser / 
                      'March' asPParser.
      monthsParser parse: 'January'
      

      或者,从集合中创建选择解析器:

      names := #('January' 'February' 'March' 'April').
      monthsParser := PP2ChoiceNode withAll: (names collect: [ :l | 
                          l asPParser ]).
      monthsParser parse: 'January'
      

      PP2 的“优化”应该很快选择正确的替代方案。

      【讨论】:

      • 这符合您的需要还是我错过了什么?
      • 这几乎就是我在问题的后半部分得出的结论,但我想知道是否有内置的东西可以“将未知长度的输入与任意块匹配”。想得更多,我想它会非常低效,因为它必须考虑整个输入,但仍然很好奇。如果可以做到,也许可以传递最大输入大小而不是固定输入大小...
      • 我明白了,不幸的是,现在 PP2 中没有这样的东西。我可以想象我们可以从一组标记转换为确定性的有限状态自动机,以在线性时间内识别一组标记中的一个标记。与选择文字标记(如我建议的那样)相比,它会获得更好的性能。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2012-11-17
      • 2016-10-07
      • 2020-11-09
      • 2019-01-15
      • 2016-10-24
      相关资源
      最近更新 更多