Last active
December 21, 2020 20:45
-
-
Save gidgid/f8cb8f5c2d4e53fa0223b2de825666d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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