So I'm trying to write my typical calculator program I typically write when learning any language, and I'm having troubles with representing the expression as an AST (by making object which represent each node type, such as BinOp, Number, etc), but am having troubles with the recursive nature of it. Here's basically what I have
type
Node = ref object of RootObj
Number = object of Node
value: int
BinOp = object of Node
left: Node
op: string
right: Node
The problem is I want the BinOp object to either take a Number node or another BinOp node as it's left and right fields. How can I achieve this? Should I just abandon using objects and try to use perhaps a tuple instead? (For background, I have light experience with C, Rust, but am much more capable with Python)Like so:
type
Operation = enum
lit, plus, minus, mul, division
Node = ref object
case op: Operation
of lit:
value: int
else:
le, ri: Node
Or if you prefer inheritance, you can extend the inheritance tree:
type
Node = ref object of RootObj
LitOrOp = ref object of Node
Number = object of LitOrOp
value: int
BinOp = object of LitOrOp
left: LitOrOp
op: string
right: LitOrOp
Araq, when I try to make a function newBinOp (which just abstracts making a binary operation from a Node), I get ".. you must provide compile-time value for discriminator 'op'" This is what the proc looks like:
proc newBinOp(left_node: Node, oper: Operation, right_node: Node): Node =
return Node(op: oper, left: left_node, right: right_node)
What am I doing wrong?