Thursday, September 29, 2011

Hi Mr. Everything's-a-Class, please copy other language's closure

If it's a hard pill to swallow for Mr. Everything's-a-Class to copy closure syntax from Mr. Method Pointers' language..

using System;

namespace TestCsharpClosures
{
    class Program
    {
        static void Main(string[] args)
        {
            var f = Test();
            Console.WriteLine("F: " + f());
            Console.WriteLine("F: " + f());
            Console.WriteLine("F: " + f());
            
            var g = Test();
            Console.WriteLine("G: " + g());
            Console.WriteLine("F: " + f());
            Console.WriteLine("G: " + g());
            Console.WriteLine("G: " + g());

            
        }

        public static Func<int> Test()
        {
            int a = 0;
            return new Func<int>(() => 
                {
                    return ++a;
                });

            // above line can be shortened to:
            // return new Func<int>(() => ++a);
        }
    }
}

Output:
F: 1
F: 2
F: 3
G: 1
F: 4
G: 2
G: 3


..at least Mr. Everything's-a-Class could copy closure syntax from its dumb kid brother:

<script type="text/javascript">

 var f = Test();
 WriteLine("F: " + f());
 WriteLine("F: " + f());
 WriteLine("F: " + f());
 
 
 var g = Test();
 WriteLine("G: " + g());
 WriteLine("F: " + f());
 WriteLine("G: " + g());
 WriteLine("G: " + g());

 function Test() {
  var a = 0;
  return function() {
   return ++a;
  };
 }

 function WriteLine(msg) {
  document.write('<div>' + msg + '</div>');
 } 
</script>

Output:

F: 1
F: 2
F: 3
G: 1
F: 4
G: 2
G: 3


Question of the week: What is the difference between a 'closure' and a 'lambda'?

Answer, there is none. Java don't have both of them :-)

No comments:

Post a Comment