Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active August 25, 2018 08:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/c811a413a4ef6dda972fe09465f94e61 to your computer and use it in GitHub Desktop.
Save JustinSDK/c811a413a4ef6dda972fe09465f94e61 to your computer and use it in GitHub Desktop.
Byte Code ABC - 1
class Num:
def __init__(self, value):
self.value = value
def evaluate(self, stack):
push(stack, self.value)
return stack
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def evaluate(self, stack):
self.left.evaluate(stack)
self.right.evaluate(stack)
add(stack)
return stack
class Mul:
def __init__(self, left, right):
self.left = left
self.right = right
def evaluate(self, stack):
self.left.evaluate(stack)
self.right.evaluate(stack)
mul(stack)
return stack
# Byte Code Instructions
def push(stack, value):
stack.append(value)
def add(stack):
r = stack.pop()
l = stack.pop()
stack.append(l + r)
def mul(stack):
r = stack.pop()
l = stack.pop()
stack.append(l * r)
# 1 + 2
print(Add(Num(1), Num(2)).evaluate([]))
# 1 + 2 + 3
print(Add(Add(Num(1), Num(2)), Num(3)).evaluate([]))
# 5 + 2 * 3
print(Add(Num(5), Mul(Num(2), Num(3))).evaluate([]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment