[英]Can AST type be recursive in ocaml?
I have attempted to translate my grammar into an AST. 我试图将我的语法转换为AST。
Can an AST type be recursive? AST类型可以递归吗? For instance, I have a production
eprime -> PLUS t eprime | MINUS t eprime | epsilon
例如,我有一个生产
eprime -> PLUS t eprime | MINUS t eprime | epsilon
eprime -> PLUS t eprime | MINUS t eprime | epsilon
eprime -> PLUS t eprime | MINUS t eprime | epsilon
. eprime -> PLUS t eprime | MINUS t eprime | epsilon
。 Is it correct to translate that to: 将其转换为:是否正确?
type eprime =
| Add of t eprime
| Minus of t eprime
| Eempty
The short answer is yes. 简短的答案是肯定的。 This is more or less exactly how you define a tree-shaped data structure.
这或多或少完全是您定义树形数据结构的方式。
A syntactically correct definition looks more like this: 语法正确的定义看起来像这样:
type eprime =
| Add of t * eprime
| Minus of t * eprime
| Empty
If you assume t
is int
(for simplicity), you can create a value of this type like this: 如果假设
t
为int
(为简单起见),则可以创建这种类型的值,如下所示:
# Add (3, Add (4, Empty));;
- : eprime = Add (3, Add (4, Empty))
Yes, an AST type can be recursive and often is. 是的,AST类型可以是递归的,并且经常是递归的。 However the correct syntax would be
Add of t * eprime
. 但是,正确的语法应
Add of t * eprime
。 Without the *
the t
would be seen as a type argument to eprime
, which doesn't take any. 如果没有
*
则t
将被视为eprime
的类型参数,它不会接受任何参数。
PS: You don't have to (and probably shouldn't) model your AST after your grammar as closely as you do. PS:您不必像语法那样紧迫地按照语法对AST进行建模。 It is perfectly okay to have "left recursion" in the AST, even if you've removed it from your grammar.
即使已将其从语法中删除,也可以在AST中具有“左递归”功能。 Similarly you don't have to encode operator precedence in your AST types the same way you do in the grammar, so for example having
Add
and Mult
in the same type is no problem. 同样,您不必像在语法中那样对AST类型中的运算符优先级进行编码,因此例如,
Add
和Mult
为相同类型是没有问题的。 With that in mind the usual definition of an AST for expressions looks more like this: 考虑到这一点,通常对表达式的AST定义看起来像这样:
type exp =
| Add of exp * exp
| Sub of exp * exp
| Mult of exp * exp
| Div of exp * exp
| FunctionCall of ident * exp list
| Var of ident
| Const of value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.