Пример #1
0
        static void Main(string[] args)
        {
            // 3 * (y + x)
            var e1 =
                new Mult(
                    new Const(3),
                    new Plus(
                        new Var("y"),
                        new Var("x")
                        )
                    );

            // 3 * y + x
            var e2 =
                new Plus(
                    new Mult(
                        new Const(3),
                        new Var("y")
                        ),
                    new Var("x")
                    );

            Console.WriteLine(e1); // (3 * (y + x))
            Console.WriteLine(e2); // ((3 * y) + x)

            var env = new Dictionary <string, int>
            {
                { "x", 2 },
                { "y", 4 }
            };

            Console.WriteLine(e1.Eval(env)); // 18
            Console.WriteLine(e2.Eval(env)); // 14

            // x^2 + xy + y^3
            var e3 =
                new Plus(
                    new Mult(
                        new Var("x"),
                        new Var("x")
                        ),
                    new Plus(
                        new Mult(
                            new Var("x"),
                            new Var("y")
                            ),
                        new Mult(
                            new Var("y"),
                            new Mult(
                                new Var("y"),
                                new Var("y")
                                )
                            )
                        )
                    );

            Console.WriteLine(e3); // ((x * x) + ((x * y) + (y * (y * y))))
            var e3x = e3.Deriv("x");
            var e3y = e3.Deriv("y");

            Console.WriteLine(e3x); // (((1 * x) + (x * 1)) + (((1 * y) + (x * 0)) + ((0 * (y * y)) + (y * ((0 * y) + (y * 0))))))
            Console.WriteLine(e3y); // (((0 * x) + (x * 0)) + (((0 * y) + (x * 1)) + ((1 * (y * y)) + (y * ((1 * y) + (y * 1))))))

            // Compute slope at point (1, 1)
            env = new Dictionary <string, int>
            {
                { "x", 1 },
                { "y", 1 }
            };

            Console.WriteLine(e3x.Eval(env)); // 3
            Console.WriteLine(e3y.Eval(env)); // 4

            // For recursive descent, because slope in y direction is steeper,
            // we'd move in that direction. Then redo the calculation and move
            // accordingly until slope becomes zero and we've reached the flat
            // part.
        }