gpt4 book ai didi

dsl - 如何在 Rebol 中使用 PARSE 评估 DSL?

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

当我学习一些 DSL 时,我意识到 Rebol 中的 Parse 方言可以是一个很好的词法分析器和解析器。 the Parse tutorial 有一个很好的例子:

    expr:    [term ["+" | "-"] expr | term]
term: [factor ["*" | "/"] term | factor]
factor: [primary "**" factor | primary]
primary: [some digit | "(" expr ")"]
digit: charset "0123456789"

probe parse "4/5+3**2-(5*6+1)" expr
;will output true

上面的代码验证表达式是否符合上面定义的“语法”。我的问题是:

  1. 如何计算或评估它?
  2. 如何表示“*”、“+”等运算符的先验?

最佳答案

Boyko Bantchev 的 code 的修改版本:

arith-eval: funct [
a-exp [string!]
] [
op-stack: copy []
num-stack: copy []
pop: func [stk /local t] [t: last stk remove back tail stk t]
do.op: func [/local op x y] [
op: to-word pop op-stack
y: pop num-stack
x: pop num-stack
append num-stack do reduce [x op y]
]
num: op: none
expr: [term any [copy op [{+} | {-}] (append op-stack op) term (do.op)]]
term: [prim any [copy op [{*} | {/}] (append op-stack op) prim (do.op)]]
prim: [copy num some digit (append num-stack to-decimal num) | {(} expr {)}]
digit: charset {0123456789}
; whitespace is not allowed between tokens

either parse a-exp expr [num-stack/1] [{wrong expression}]
]



>> arith-eval "12+34*56-89/2"
== 1871.5
>>

关于dsl - 如何在 Rebol 中使用 PARSE 评估 DSL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767814/

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