Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Last active June 12, 2019 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepasflo/5c574c3a1fb16e85b560d029366e8d0f to your computer and use it in GitHub Desktop.
Save pepasflo/5c574c3a1fb16e85b560d029366e8d0f to your computer and use it in GitHub Desktop.

Writing eval() for simple math expressions

Rather than starting with lexing and parsing, this week we just assume we have those bits already working, so that we can jump straight to eval().

video:

recording of the meeting

diagrams:

diagrams used during the meeting:

Screen Shot 2019-05-30 at 2 26 16 PM

Screen Shot 2019-05-30 at 2 26 27 PM

Screen Shot 2019-05-30 at 2 26 35 PM

whiteboard notes:

whiteboard notes

#!/usr/bin/env python
def add(a,b):
return a + b
def multiply(a,b):
return a * b
def flookup(toktype):
if toktype == "plus":
return add
elif toktype == "mult":
return multiply
def matheval(node):
if node["token"]["type"] == "num":
return float(node["token"]["text"])
else:
f = flookup(node["token"]["type"])
l = matheval(node["left"])
r = matheval(node["right"])
return f(l,r)
t1 = { "type": "num", "text": "1" }
tp = { "type": "plus", "text": "+" }
t2 = { "type": "num", "text": "2" }
tm = { "type": "mult", "text": "*" }
t3 = { "type": "num", "text": "3" }
n1 = { "token": t1, "left": None, "right": None }
np = { "token": tp, "left": None, "right": None }
n2 = { "token": t2, "left": None, "right": None }
nm = { "token": tm, "left": None, "right": None }
n3 = { "token": t3, "left": None, "right": None }
# *
# / \
# + 3
# / \
# 1 2
tree = nm
nm["left"] = np
nm["right"] = n3
np["left"] = n1
np["right"] = n2
print matheval(tree) # 9
# +
# / \
# 1 *
# / \
# 2 3
tree = np
np["left"] = n1
np["right"] = nm
nm["left"] = n2
nm["right"] = n3
print matheval(tree) # 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment