コード例 #1
0
        public static void Main()
        {
            var e1 = new Add(new CstI(17), new Var("z")); // => Add(17, z)

            // WriteLine automatically calls .ToString on objects passed to it
            Console.WriteLine(e1);

            // (ii) Create three more expressions and print them
            //      Easter egg: I totally stole them from Intro2.fs
            var e2 = new CstI(17);                       // => 17
            var e3 = new Add(new CstI(3), new Var("a")); // => Add(3, a)
            var e4 = new Add(new Mul(new Var("b"), new CstI(9)), new Var("a"));

            // => Add(Mul(b, 9), a)

            Console.WriteLine(string.Format("{0}\n{1}\n{2}", e2, e3, e4));

            // (iii) Add the eval function to each subclass of `Expr`
            var env = new Dictionary <string, int> {
                { "x", 5 },
                { "y", 42 }
            };
            var e5 = new Add(new Var("x"), new CstI(5));

            Console.WriteLine(e5.Eval(env)); // => 10

            // (iv) Add the simplify function to each subclass of `Expr`
            var e6 = new Add(new Var("x"), new CstI(0)); // => x
            var e7 = new Sub(new Var("x"), new CstI(0)); // => x
            var e8 = new Mul(new CstI(5), new CstI(0));  // => 0
            var e9 = new Mul(new Var("x"), new CstI(1)); // => x

            Console.WriteLine(string.Format("{0}\n{1}\n{2}\n{3}",
                                            e6.Simplify(), e7.Simplify(), e8.Simplify(), e9.Simplify()));
        }