|
| 1 | +// Copyright 2025 International Digital Economy Academy |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +///| |
| 16 | +enum Expr { |
| 17 | + Add(Expr, Expr) |
| 18 | + Sub(Expr, Expr) |
| 19 | + Mul(Expr, Expr) |
| 20 | + Div(Expr, Expr) |
| 21 | + Lit(Int) |
| 22 | + Var(String) |
| 23 | +} derive(Show, ToJson, Eq) |
| 24 | + |
| 25 | +///| |
| 26 | +fn simplify(e : Expr) -> Expr { |
| 27 | + match e { |
| 28 | + Add(e1, Lit(0)) => simplify(e1) |
| 29 | + Add(Lit(0), e2) => simplify(e2) |
| 30 | + Mul(e1, Lit(1)) => simplify(e1) |
| 31 | + Mul(Lit(1), e2) => simplify(e2) |
| 32 | + Sub(e1, e2) if e1 == e2 => Lit(0) |
| 33 | + // guard is useful for in-exhaustive match |
| 34 | + // otherwise the else condition will be duplicated |
| 35 | + Mul(Lit(0), _) => Lit(0) |
| 36 | + Mul(_, Lit(0)) => Lit(0) |
| 37 | + _ => e |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +///| |
| 42 | +test "simplify" { |
| 43 | + let _ignored = Add(Div(Lit(1), Lit(2)), Div(Lit(1), Lit(2))) |
| 44 | + let e = Sub(Mul(Lit(1), Var("x")), Mul(Lit(1), Var("x"))) |
| 45 | + let simplified = simplify(e) |
| 46 | + inspect!(simplified, content="Lit(0)") |
| 47 | +} |
0 commit comments