Hi, total newcomer here, so apologies if this isn't a clear question. As a basic experiment, I'm thinking about how to represent a graph, in which I have two types of objects: Branch: This object has a list of children. Leaf: This object is an endpoint with no children.
This means that each branch's "children" field is a sequence of objects, where each object is either a branch of a leaf. So the question is how to represent this in Nim.
Does this make sense? Is 3) the only viable option in Nim, or am I missing something?
Thank you.
i'd recommend you read through the nim tutorial and manual, the sections on variants in the tutorial and manual in particular.
type NodeKind = enum
Leaf,
Branch
type Node = object
case kind: Nodekind
of Leaf:
value: int # or whatever
of Branch:
kids: seq[Node]
is very typical Nim code, and how Nim itself is implemented.
to handle variants in a proc you also use the case statement
import std/[sequtils]
proc nd(i:int):Node = Node(kind: Leaf, value: i)
proc nd(n:Node):Node = n
proc nd(x:varargs[Node]):Node = Node(kind: Branch, kids: @x)
proc sum(node: Node):int =
case node.kind
of Leaf:
return node.value
of Branch:
return foldl(node.kids,a+sum(b),0)
let n = nd(nd(3),nd(4),nd(nd(5),nd(6)))
assert sum(n)==18