Hi there, I'm very new to Nim.
I have some code:
type
LitKind* = enum
NumLit,
StrLit,
NilLit,
BoolLit
LitType* = object
case litKind*: LitKind
of NumLit: n*: float64
of StrLit: s*: string
of BoolLit: b*: bool
of NilLit: discard
Expr = ref object of RootObj
Literal = ref object of Expr
value: LitType
BinOp = ref object of Expr
left, right: Expr
op: string
var left = Literal(value: LitType(litKind: NumLit, n: 5.0))
var right = Literal(value: LitType(litKind: NumLit, n: 6.0))
var add = BinOp(left: left, op: "+", right: left)
echo add[]
echo add[].left
the first echo statement works, although I'm not super sure why I need to add the square brackets on add.
But, the second echo statement does not work. How can I access add.left?
Thanks. What I'm seeing is that: echo add[] prints:
(left: ..., right: ..., op: "+")
but echo add.left[] just prints:
()
Like I said ref's do not have a $ defined and when the default $ for objects is called it replaces shows ... for the output. This can be seen in the following aswell
type NotInt = distinct int
echo (NotInt(10), )
You need to implement your own $ to change the behaviour for instance:
type NotInt = distinct int
proc `$`(n: NotInt): string = "NotInt(" & $int(n) & ")"
echo (NotInt(10), )
I'm not super sure why I need to add the square brackets on add.
[] is the dereferencing sign, similiar to * in C.
proc `$`*[T: typed](x: ref T): string = "->" & $(x[])
type MyType = ref object
child: MyType
val: int
var a = MyType()
a.child = a
echo a
Way too naive it requires a cyclic check