Last active
December 29, 2022 09:35
-
-
Save joelgrus/c6a2186b3f8eec6f48721606550979da 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
""" | |
"algebraic data types" in python | |
""" | |
from __future__ import annotations | |
from dataclasses import dataclass | |
@dataclass | |
class Value: | |
value: int | |
@dataclass | |
class Add: | |
left: Expr | |
right: Expr | |
@dataclass | |
class Mul: | |
left: Expr | |
right: Expr | |
Expr = Value | Add | Mul | |
def eval(expr: Expr) -> int: | |
match expr: | |
case Value(value): | |
return value | |
case Add(left, right): | |
return eval(left) + eval(right) | |
case Mul(left, right): | |
return eval(left) * eval(right) | |
def rpn(s: str) -> Expr: | |
"""parse reverse polish notation""" | |
stack: list[Expr] = [] | |
for token in s.split(): | |
match token: | |
case "+": | |
right = stack.pop() | |
left = stack.pop() | |
stack.append(Add(left, right)) | |
case "*": | |
right = stack.pop() | |
left = stack.pop() | |
stack.append(Mul(left, right)) | |
case _: | |
stack.append(Value(int(token))) | |
return stack.pop() | |
if __name__ == "__main__": | |
expr = rpn("1 2 + 3 4 + *") | |
print(expr, "=", eval(expr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment