dongzhao8233 2016-01-22 19:32
浏览 96
已采纳

简洁的语法来解析诸如“ abab”或“ baba”之类的交替字符的字符串

I am working on a toy parser in golang just to learn the language. I added a test case with grammar covering the following cases:

Valid:
a, ab, aba, ababababababa, ababababab
b, ba, bab, babababababab, bababababa

Invalid:
abb, baa

a is always followed by b and vice versa.

Now the grammar in my parser looks like that (I omit the surrounding code for sake of brevity):

    "expr": Or(Ref("A"), Ref("B")),
    "A": And(
        a,
        Optional(
            And(
                b,
                Optional(Ref("A"))))),
    "B": And(
        b,
        Optional(Ref("A")))

Where

a - exact match for "a" character
b - exact match for "b" character
"A", "B", "expr" - names of the parts of the grammar that can be referred
                   later with Ref("A")
And      - consume sequence of expressions
Or       - consume any of the expressions
Ref      - refer to other expression (allows recursion)
Optional - make the expression non-obligatory

I guess it is not the most succinct way to describe this grammar. How to make it more compact?

Related:


EDIT:

The BNF answer from Filip can be written in my syntax as:

    "expr": Or(Ref("A"), Ref("B")),
    "A":    Or(And(a, Ref("B")), a),
    "B":    Or(And(b, Ref("A")), b)
  • 写回答

1条回答 默认 最新

  • dpxnrx11199 2016-01-22 19:40
    关注

    The BNF grammar you have is this:

    expr ::= A | B
    A ::= "a" B | "a"
    B ::= "b" A | "b"
    

    which I think translates to this using your syntax:

    "expr": Or(Ref("A"), Ref("B")),
    "A": And(
        a,
        Optional(Ref("B"))),
    "B": And(
        b,
        Optional(Ref("A")))
    

    Note that it is important to check terminals ("a", "b") before non-terminals (Ref(x)), or you'll get an infinite loop. It would always try to see if it could match another A or B to the end of the string, and then another, and another, causing a never ending recursion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝