Skip to content

Instantly share code, notes, and snippets.

@gidgid
Last active December 21, 2020 20:45
Show Gist options
  • Save gidgid/f8cb8f5c2d4e53fa0223b2de825666d9 to your computer and use it in GitHub Desktop.
Save gidgid/f8cb8f5c2d4e53fa0223b2de825666d9 to your computer and use it in GitHub Desktop.
from adt import Case, adt
@adt
class Expression:
LITERAL: Case[float]
ADD: Case["Expression", "Expression"]
SUBTRACT: Case["Expression", "Expression"]
MULTIPLY: Case["Expression", "Expression"]
DIVIDE: Case["Expression", "Expression"]
def evaluate(expr: Expression):
return expr.match(
literal=lambda l: l,
add=lambda x, y: evaluate(x) + evaluate(y),
subtract=lambda x, y: evaluate(x) - evaluate(y),
multiply=lambda x, y: evaluate(x) * evaluate(y),
divide=lambda x, y: evaluate(x) / evaluate(y),
)
def test_expression_evaluation():
expression = Expression.MULTIPLY(
Expression.ADD(Expression.LITERAL(1.0), Expression.LITERAL(2.0)),
Expression.LITERAL(5.0),
)
value = evaluate(expression)
assert value == (1 + 2) * 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment