gpt4 book ai didi

parsing - 递归下降解析 : high precedence unary operators

转载 作者:行者123 更新时间:2023-12-04 04:34:59 26 4
gpt4 key购买 nike

我已经想出了如何优先实现二元运算符,像这样(伪代码):

method plus
times()

while(consume(plus_t)) do
times()
end
end

method times
number()

while(consume(times_t))
number()
end
end

// plus() is the root operation

// omitted: number() consumes a number token

所以当我解析 4 + 5 * 6它会:
  • 加上
  • 乘以
  • 数量(消耗 4 个)
  • plus_t 消耗
  • 乘以
  • 数量(消耗 5 个)
  • times_t 消耗
  • 数量(消耗 6 个)

  • 但是,当我尝试添加 minus 时方法(前缀减去 -4 ,而不是中缀减去 4 - 5 ):
    method minus
    consume(minus_t)
    plus()
    end

    它的优先级非常低,所以 -4 + 5变成 -(4 + 5)而不是 (-4) + 5这是不可取的。

    我能做些什么来制作一个高优先级的一元运算符?

    最佳答案

    您还没有说明要在层次结构中的哪个位置添加 minus方法,但看起来您将其添加到 plus 上方并使其成为根。

    想要的话最后需要放unary -具有比 + 更高的优先级和 * .

    在你的伪代码中,这样的事情应该可以工作:

    method times
    minus()

    while(consume(times_t))
    minus()
    end
    end

    method minus
    if(consume(minus_t))
    // next number should have a unary minus attached
    number()
    else
    number()
    end
    end

    这些天我正在学习解析器,所以我根据您的伪代码编写了一个完整的解析器,它在 LiveScript 中,但应该很容易理解。

    编辑:在 jsfiddle.net 上运行示例 - http://jsfiddle.net/Dogbert/7Pmwc/
    parse = (string) ->
    index = 0

    is-digit = (d) -> '0' <= d <= '9'

    plus = ->
    str = times()
    while consume "+"
    str = "(+ #{str} #{times()})"
    str

    times = ->
    str = unary-minus()
    while consume "*"
    str = "(* #{str} #{unary-minus()})"
    str

    unary-minus = ->
    if consume "-"
    "(- #{number()})"
    else
    number()

    number = ->
    if is-digit peek()
    ret = peek()
    advance()
    while is-digit peek()
    ret += peek()
    advance()
    ret
    else
    throw "expected number at index = #{index}, got #{peek()}"

    peek = ->
    string[index]

    advance = ->
    index++

    consume = (what) ->
    if peek() == what
    advance()
    true

    plus()


    console.log parse "4+5*6"
    console.log parse "-4+5"
    console.log parse "-4*-5+-4"

    输出:
    (+ 4 (* 5 6))
    (+ (- 4) 5)
    (+ (* (- 4) (- 5)) (- 4))

    PS:你可能想看看 Operator-precedence Parsers用于相对容易地解析复杂的优先级/关联性。

    关于parsing - 递归下降解析 : high precedence unary operators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19884502/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com