private Expr Diff(Expr expr) { if (expr.A == Action.A) { if (expr.LS == null && expr.RS == null) { Expr left = Diff(expr.LE); Expr right = Diff(expr.RE); return new Expr(Action.A, null, left, null, right); } else if (expr.LS == null) { Expr left = Diff(expr.LE); string right = (isX(expr.RS)) ? "1" : "0"; return new Expr(Action.A, null, left, right, null); } else if (expr.RS == null) { Expr right = Diff(expr.RE); string left = (isX(expr.LS)) ? "1" : "0"; return new Expr(Action.A, left, null, null, right); } else { string left = (isX(expr.LS)) ? "1" : "0"; string right = (isX(expr.RS)) ? "1" : "0"; return new Expr(Action.A, left, null, right, null); } } else { if (expr.LS == null && expr.RS == null) { Expr left = new Expr(Action.M, null, Diff(expr.LE), null, expr.RE); Expr right = new Expr(Action.M, null, expr.LE, null, Diff(expr.RE)); return new Expr(Action.A, null, left, null, right); } else if (expr.LS == null) { Expr left = new Expr(Action.M, null, Diff(expr.LE), expr.RS, null); Expr right = new Expr(Action.M, null, expr.LE, (isX(expr.RS)) ? "1" : "0", null); return new Expr(Action.A, null, left, null, right); } else if (expr.RS == null) { Expr left = new Expr(Action.M, (isX(expr.LS)) ? "1" : "0", null, null, expr.RE); Expr right = new Expr(Action.M, expr.LS, null, null, Diff(expr.RE)); return new Expr(Action.A, null, left, null, right); } else return new Expr(Action.M, "0", null, "0", null); } }
static void Main(string[] args) { Expr expr = new Expr(Expr.Action.M, "X", null, null, new Expr(Expr.Action.A, "X", null, "1", null)); Expr diff = expr.Diff(); Console.WriteLine("Expr: " + expr.ToString()); Console.WriteLine("Diff: " + diff.ToString()); Mult exp = new Mult(new X(), new Add(new X(), new Num(1))); Console.WriteLine(exp.Print()); Console.WriteLine(exp.Diff().Print()); }
public Expr(Action a, string sl, Expr el, string sr, Expr er) { A = a; LS = sl; RS = sr; LE = el; RE = er; }