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 :-)

Monday, September 12, 2011

Postgresql 9.1 is released now

Download Postgresql 9.1 now

One neat feature, we can now omit extraneous fields on GROUP BY, as long as primary key is already there


create table person
(
person_id serial not null primary key,
firstname text not null,
lastname text not null,
address text not null
);

create table visit
(
visit_id serial not null primary key,
person_id int not null references person(person_id),
url text not null
);


select
    p.person_id,
    p.firstname, p.lastname, p.address, 
    count(*)
from
    person p
    join visit v on p.person_id = v.person_id
group by p.person_id
    -- ,p.firstname, p.lastname, p.address; -- omitting other fields is now possible on 9.1


And it's still the same disciplined Postgresql
select    
    p.firstname, p.lastname, count(*)
from
    person p
    join visit v on p.person_id = v.person_id
group by p.firstname  -- this is not allowed, it's confusing which lastname to pick