Last active
March 1, 2022 02:44
-
-
Save Zeta611/03a9025621c0a987fff8bcbded90c036 to your computer and use it in GitHub Desktop.
[ADT in Python] Algebraic data type (sum type) in Python #demo
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 dataclasses import dataclass | |
@dataclass(frozen=True) | |
class Var: | |
name: str | |
@dataclass(frozen=True) | |
class Int: | |
val: int | |
@dataclass(frozen=True) | |
class Add: | |
left: "Exp" | |
right: "Exp" | |
@dataclass(frozen=True) | |
class Mul: | |
left: "Exp" | |
right: "Exp" | |
@dataclass(frozen=True) | |
class Assgn: | |
var: str | |
val: "Exp" | |
exp: "Exp" | |
Exp = Var | Int | Add | Mul | Assgn | |
Env = dict[str, int] | |
def eval(exp: Exp, env: Env) -> int: | |
match exp: | |
case Var(name): | |
return env[name] | |
case Int(val): | |
return val | |
case Add(left, right): | |
return eval(left, env) + eval(right, env) | |
case Mul(left, right): | |
return eval(left, env) * eval(right, env) | |
case Assgn(var, val, exp): | |
new_env = env.copy() | |
new_env[var] = eval(val, env) | |
return eval(exp, new_env) | |
exp: Exp = Assgn( | |
"x", | |
Int(2), | |
Mul( | |
Assgn("x", Int(7), Add(Var("x"), Assgn("y", Add(Int(3), Int(8)), Var("y")))), | |
Var("x"), | |
), | |
) | |
print(eval(exp, {})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment