Created
August 1, 2023 22:06
-
-
Save AnthonyMikh/7b4c52681aff1e243dbcf95b51d69877 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
enum Expr { | |
Lit(i32), | |
Neg(Box<Self>), | |
Add(Box<Self>, Box<Self>), | |
} | |
fn lit(x: i32) -> Expr { | |
Expr::Lit(x) | |
} | |
fn neg(e: Expr) -> Expr { | |
Expr::Neg(e.into()) | |
} | |
fn add(lhs: Expr, rhs: Expr) -> Expr { | |
Expr::Add(lhs.into(), rhs.into()) | |
} | |
fn add3(a: Expr, b: Expr, c: Expr) -> Expr { | |
add(a, add(b, c)) | |
} | |
#[test] | |
fn primitive_cases() { | |
assert_eq!(lit(5).to_string(), "5"); | |
assert_eq!(lit(-5).to_string(), "-5"); | |
assert_eq!(neg(lit(2)).to_string(), "-2"); | |
assert_eq!(neg(lit(-2)).to_string(), "-(-2)"); | |
assert_eq!(add(lit(2), lit(3)).to_string(), "2 + 3"); | |
} | |
#[test] | |
fn addition_associativity() { | |
assert_eq!(add(lit(1), add(lit(2), lit(3))).to_string(), "1 + 2 + 3"); | |
assert_eq!(add(add(lit(1), lit(2)), lit(3)).to_string(), "1 + 2 + 3"); | |
} | |
#[test] | |
fn adding_negative_literals() { | |
assert_eq!(add(lit(1), lit(-2)).to_string(), "1 + (-2)"); | |
assert_eq!(add(lit(-1), lit(2)).to_string(), "-1 + 2"); | |
assert_eq!(add(lit(-1), lit(-2)).to_string(), "-1 + (-2)"); | |
} | |
#[test] | |
fn adding_negated_expressions() { | |
assert_eq!(add(lit(1), neg(lit(2))).to_string(), "1 + (-2)"); | |
assert_eq!(add(lit(1), neg(lit(-2))).to_string(), "1 + (-(-2))"); | |
assert_eq!(add(lit(1), neg(add(lit(3), lit(4)))).to_string(), "1 + (-(3 + 4))"); | |
} | |
#[test] | |
fn summing_negatives() { | |
assert_eq!(add3(lit(-1), lit(-2), lit(3)).to_string(), "-1 + (-2) + 3"); | |
assert_eq!(add3(lit(-1), lit(-2), lit(-3)).to_string(), "-1 + (-2) + (-3)"); | |
assert_eq!(add3(lit(-1), lit(-2), neg(lit(3))).to_string(), "-1 + (-2) + (-3)"); | |
assert_eq!(add3(lit(-1), neg(lit(2)), lit(3)).to_string(), "-1 + (-2) + 3"); | |
assert_eq!(add3(lit(-1), neg(lit(2)), neg(lit(3))).to_string(), "-1 + (-2) + (-3)"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment