Skip to content

Instantly share code, notes, and snippets.

@matthiaswh
Last active December 7, 2018 19:45
Show Gist options
  • Save matthiaswh/4733651d6b1165f5c8938ca81e59f597 to your computer and use it in GitHub Desktop.
Save matthiaswh/4733651d6b1165f5c8938ca81e59f597 to your computer and use it in GitHub Desktop.
playing with types and inheritance in nim-lang
import strutils # provides parseInt for us
type
Node = ref object of RootObj
value: string
active: bool
type
NumNode = ref object of Node
type
BinOp = ref object of Node
left, right: Node
op: string
var add = BinOp(
left: NumNode(value: "7"),
op: "+",
right: NumNode(value: "9"),
active: true
)
echo add[]
# > (left: ...right: ...op: "+", value: "", active: true)
var multiply = BinOp(
left: add,
op: "*",
right: NumNode(value: "3"),
active: true
)
echo multiply[]
# > (left: ...right: ...op: "*", value: "", active: true)
echo multiply[]
# > (left: ...right: ...op: "*", value: "", active: true)
proc interpret(node: Node): int =
if node of NumNode:
return parseInt(node.value)
if node of BinOp:
let n = BinOp(node)
if n.op == "+":
return interpret(n.left) + interpret(n.right)
if n.op == "*":
return interpret(n.left) * interpret(n.right)
echo interpret(multiply)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment