Thursday, April 29, 2004

I thought of putting together some of my old mails and user group posting as blog entries, with some patches so that they are’ blogopatible’. They would have ended up on my blog, if I had a blog when I made these posts. I feel some of these are of lasting importance, at least with respect to the impressions they had on me.

 

All of these are personal opinions, probably more relevant in the context that they were originally written.

 

-----Original Message-----
From: James, Roshan
Sent:
Tuesday, December 09, 2003
11:57 PM
 Subject: XAML and markups: Introducing WFML - WinForms Markup Language

Hi Folk,

 

Ever since Linux Bangalore I have been thinking about something that Miguel de Icaza had demoed on stage. He was showing Mono’s UI, Glade, and showed how Glade generates UI from XML markup. They (Miguel and Nat) were also joking as to how XAML is an idea that they had thought of 6 years back – the idea of using XML markup for representing UI and separating 'business logic' from UI.

 

            He also went on to show how Glade is used to generate GTK# UI in linux. A '.glade' file is simply an xml file that contains tags that correspond to the properties of the controls (or widgets as they call them).

 

(I pulled glade file off the net to give you an idea of what it looks like

 

< widget class="GtkWindow" id="window2">

  < property name="visible">True< /property>

  < property name="title" translatable="yes">window2< /property>

  < property name="type">GTK_WINDOW_TOPLEVEL< /property>

  < property name="window_position">GTK_WIN_POS_NONE< /property>

  < property name="modal">False< /property>

  < property name="resizable">True< /property>

  < property name="destroy_with_parent">False< /property>

 

  < child>

    < widget class="GtkButton" id="button1">

      < property name="border_width">10< /property>

      < property name="visible">True< /property>

      < property name="can_focus">True< /property>

      < property name="label" translatable="yes">button1< /property>

      < property name="use_underline">True

      < property name="relief">GTK_RELIEF_NORMAL< /property>

    < /widget>

  < /child>

< /widget>

 

)

 

The strange thing was how they used glade files - in XAML you compile the xml file to generate a class (or what MS calls a partial class, one that can be extended elsewhere). In glade they did no such thing, they simple wrote a cs file and called one Glade API function passing it the name of '.glade' file. That returned some kind of object and presto they had their UI. Now the claim was that this really separates the UI from the code and as a matter of fact the XML can be chnaged after the exe file has been compiled. Changes to the XML will reflect in the UI without recompilation of anything. They also mentioned that Microsoft hasn’t figured out how to do this yet.

 

(Here is fragment of c# code that uses the .glade

 

                using Gtk;

                using Gnome;

                using Glade;

                using GtkSharp;

 

        public class GladeTest

                {

                                /* If you want to access the glade objects you have to "import" them.

                                 * This is not required, but else you can only work with the

                                 * pre-defined signal handlers */

                                [Glade.Widget]     

                                Button button1;

 

                                public GladeTest (string[] args)

                                {

                                                Application.Init();

 

                                                /* This loads the glade file glade.glade,

                                                 * selects window2 and connects it to the current object,

                                                 * which is the class GladeTest here. */

                                                Glade.XML gxml = new Glade.XML ("file.glade", "window2", null);

                                                gxml.Autoconnect (this);

 

                                                button1.BorderWidth=10;

 

                                                Application.Run();

                                }

)

 

            Now this got me thinking about how they implemented this dynamic behavior - as result of which WFML was born. It was rather surprising how easy this was to do. I am sure Miggy's code will be better and more optimized, but I think my general direction is correct.

 

WFML, in short provides (or at least hopes to provide) a markup language for UI that simply does not have to compiled (in the conventional sense). WFML UI is actually WinForms based UI, WFML by itself cannot add any features that are not present in WinForms. What it does is that it lets you write very clean looking code that does not have a clutter for UI itself. The entire UI of the program is expressed in an external XML file, called a .wfml file. Now if you have ever tried writing a Win forms application by hand without studio, you will remember how hard it is to remember so many of the house-keeping things required - take a look at some WFML based code:

 

//win.cs

using System;

using System.Windows.Forms;

using System.Windows.Forms.Markup;

 

 

class CMain

{

        static void Main()

        {

                IAttachable win = new Wfml().CreateUserInterface("win.wfml","MainWindow");

                Application.Run((Form)win);

        }

}

 

Simple ? This is a C# file that uses the WFML library. The markup lib being a pure .Net assembly can be used by any .Net language, - C#, VB, C++, Jscript, VJ# etc. Now what you need is a WFML file that specifies the UI. And you simply write the .wfml file like this (win.wfml):

 

 

        < Window

                Name="MainWindow"

                Height="200"

                Width="400"

        />

 

As you can see, the WFML is simply an XML file with certain tags that the WFML library understands. The advantage of using something like WFML is that you can completely change this XML at will and the UI of your program can be completely changed.

 

Now compile the cs:

   

csc /t:winexe /r:System.Windows.Forms.Markup.dll win.cs

 

Run win.exe and you will see an empty window

 

The following .wfml code displays a button and a text box for the same win.exe program. The program need not be edited or recompiled, only the .wfml file needs to be changed.

 

< Window

        Name="MainWindow"

        Height="200"

        Width="400"

       

        Text="Main Window"

>

        < Button Name="mybutton"

                Top="10"

                Text="Click Me"

        />

        < TextBox

                Name="tbox"

                Top="40"

                Left="5"

                Width="200"

        />

 

(What tags and attributes are allowed within a WFML? Every attribute that you set in a tag has to be a property of the corresponding WinForms type. That is to say that if you want to put a attribute called ‘Text’ in the ‘Window’ tag, then the class System.Windows.Form.Window should support a property called Text. WFML being a very simple system is case sensitive and provides no error feedback if something is wrong.)

 

And you can even attach event handlers and write back to the UI:

 

using System.Windows.Forms;

using System.Windows.Forms.Markup;

using System;

 

class CMain

{

        public TextBox tbox;

         

        public void clicked(object sender, EventArgs e)

        {

                tbox.Text+="+ ";

        }

        

        static void Main()

        {

                IAttachable win = new Wfml().CreateUserInterface("win.wfml","MainWindow");

                CMain cm = new CMain();

                win.AttachConsumer(cm);

               

                Application.Run((Form)win);

        }

}

 

Do try some WFML, the supported types are Button, TextBox and Label - but I guess the rest can be added easily.  Now I don't think this was anywhere as hard as they were making it out to be on stage.

 

Roshan James

------------------------------

 

 

You can download the WFML.zip file here. This also contains the demos that I had for this UG post.  While I never did continue on the WFML, folk did mail me back asking about the WFML assuming it was part of a larger UI framework.

 

Of course, capital negatives of the approach are that there is no IDE to ease development of WFML and such, but the idea itself is rather interesting.

 

How WFML actually works, as you might have guess is that it uses reflection API to dynamically generate a System.Windows.Form type that is customized according to the WFML file. This runtime generated type also runs reflection based code on its caller and appropriately latches up event handlers dynamically. Also it uses reflection to assign references of the caller to classes to the actual objects created in the generated Form class.

 

You however need not compare XAML to WFML or like approaches because XAML is a whole different beast. Differences start with be67ing vectored based don’t stop any time soon.

Thursday, April 29, 2004 5:49:08 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  | 
 Tuesday, April 27, 2004

I thought of putting together some of my old mails and user group posting as blog entries, with some patches so that they are’ blogopatible’. They would have ended up on my blog, if I had a blog when I made these posts. I feel some of these are of lasting importance, at least with respect to the impressions they had on me.

 

All of these are personal opinions, probably more relevant in the context that they were originally written.

 

-----Original Message-----

From: James, Roshan

Sent: Friday, December 05, 2003 5:37 PM

To: MVP Mailing List

Subject: An Audience with Miguel

 

 

written in a hurry:

 

An Audience with Miguel

 

Hi, yesterday Pooja and I got to catch a part of Linux Bangalore, the annual Linux convention, and I thought that it would be nice to write to mvplist and share our experiences. We had missed the dates for the event and I was rather shocked at having missed a chance to see Miguel De Icaza in person.

 

Miguel, for those who don't know about him, is the creator of mc (the Midnight commander), Gnome (the rather popular open source desktop) and in recent days the lead for the Mono project. The Mono project is the only other major (when I say major here, it is not that I don’t know of dotGNU and other attempts, it is because I personally feel that Mono is more complete than those) .Net implementation outside of the Microsoft world. Mono runs on Windows as well as on Linux and probably other Unix flavors. This guy has been famous/notorious in the open source community for writing papers like 'Lets make Unix not suck' and has a rather 'misfit' personality for the typical religious ramblings of the free software types. In short this man has written his own windowing systems, his own .Net, his own enterprise servers and was running his own company called Ximian.

 

Ximian has been recently bought by Novell making Novell a major player in the open source world. Novell has also bought Suse - major Linux flavour and Novell seems to be on the path of becoming a significantly important open source company, along the lines of maybe Red Hat and such. However unlike Redhat and many of the 'Linux companies', Novell has a focus on delivering products rather than making Linux distributions and delivering them dirt cheap or free if they have to, to get into the market. So in short Miguel is as much a demi-god as our own Anders Hejlsberg, or Don Box.

 

The above paragraph was to set things in perspective. This is the mono website (http://www.go-mono.com/). Having been rather disappointed to have missed Linux Bangalore dates and missed Miguel, I happened to check their talk schedules by sheer accident around 11.30 yesterday. As fate would have it, there was a talk by Miguel, his last one, scheduled at 12.00. After a ~12km drive and some conversation with the registration counter we were at the IISC Bangalore venue – the last time I was here, I was attending the Microsoft Tech Ed.

 

One thing you notice up front as you enter is a big banner of Abdul Kalam, our president. The poster quotes him saying that it is probably not good to have important national software depending on proprietary solutions as proprietary solutions and highly dependant on the market that the vendors cater to and that sort of unreliability is probably not a good thing. And also that free software would really help a poorer country like ours as prices of commercial software are rather high. At least that was the message in spirit - don't think I have got any of his words right.

 

The crowd, as far as I could say was probably the same caliber as the technical crowd I usually get to interact with at UGs and various .Net technology events. Probably not as good in some respects - but there was this thing in the air that they were all up to 'something important'. Also one other thing that was noticeable was the set of demo computers setup, where people could sit down and try out many of the software that was being talked about in the talks.

 

Miguel's talk was at the main hall of the IISC venue (those who know the place will know what I mean). He was accompanied by Nat Friedman of Novell, a fellow mono-ist. What happened at the talk was something I wasn't prepared for. For those of you who have a mental image of Miguel by now, this guy is young, in his early twenties. He was carrying a digital SLR camera with a hefty lens and flash addons and was dressed in baggy jeans and black t-shirt. So was the other guy Nat. Now these guys hop on stage (literally), sit down on the floor - one of them rolls out a length of cable that he had wrapped around his neck the whole while. They pull out two laptops and they get a network setup between their systems and the presentation starts up.

 

The presentation showed of some parts of C# , web services, GTK# for windowing, GTK + for generating XML markup for the UI (and some jokes about how XAML is a copy of their own 6 year old idea) and more. These guys did the whole presentation sitting or lying down on the floor of the stage, sometimes editing the presentation right there in front of the audience, pulling jokes on each other and writing code the whole time for a full hour - and the whole thing was on their own Mono. Awesome.

 

After the talk Pooja and I met up with Miguel and introduced ourselves as being from the ‘dark side’ (He asked me if I was an ASP.Net developer because of all the questions I was asking from what otherwise seemed to be a relatively .Net ignorant audience. He was interested in the fact that I was an MVP.) and asked him if we could meet him sometime later, maybe over dinner or so. He was fine with that – that however was not to happen as his schedule did not allow him to. Various activities were planned for him for the whole of the next day (today, Friday) and he was going to flying on Saturday. He did promise to talk to our .Net user group the next time he is in India (expected to be in the second quarter of next year). I had to get back to office so I had to leave then; with the intention of returning for Jani's talk a little later in the evening.

 

I managed to sneak out of office again to attend the talk by Mr. Janakiram (I hope you know him - he heads Microsoft India's academic/university relationship program). Along with Jani was Mr. Gaurav Daga (he is a Program Manager of the famous Services for Unix team at Hyderabad; SFU won last years best open source software of the year award). Their venue didn't do any justice to their talk. Their talk was scheduled at one of the smaller halls and the crowd was so packed for the talk that I couldn't get close to the door of the hall. Jani and Gaurav as usual pulled a great show. They were talking about the new 'Unix' being built in windows ;) (Their demo was rather awesome: they took a Unix app ran it on windows literally, they wrote .Net code and exposed it as a web service, they built a proxy around the service and consumed the proxy as a COM component which was used by excel which was used to dump – did I miss anything?)  

 

All the while, from when he finished his talk, Miguel and his gang were there in the main lobby, showing off code or sitting or taking photographs or ready to talk to anyone at all about anything. When he was not doing that he would be sitting around in some corner with Nat typically typing away at a piece of code he was working on.

 

Since I couldn't get to listen to Jani at all due to the crowd and having driven the ~12km stretch in Bangalore traffic for the third time that day, I was walking around looking rather moody. Miguel then walks up to me, 'Microsoft dude', and gets our picture taken together. He kept calling me 'Microsoft dude' and he himself wanted to be called 'The Dude'; it was interesting talking to him.

 

I wanted to introduce Jani and Gaurav to Miguel and Nat after their talk. It was funny because on meeting Jani and Gaurav, Miguel seemed to freeze up a little bit - I think it's that Microsoft-effect. But on the whole they were nice folk. And Jani and Gaurav were good too. Jani mentioned how he wrote a wrapper around the 'Tk' widget library and called it a windows forms assembly and got to run some regular winforms code on Linux’

 

In retrospect, if I wanted to pick faults with the event I could and I could say that the organizing was bad, because the projector was shaky and the stage wasn't setup properly and the food was bad and all that and be complacent about the whole thing. But looking at the good side, you see guys who are probably the gods of their community actually sitting around with the developers showing off their code and laughing and talking rather that running off after a talk or sitting in a separate area. These are probably something's that we could learn from these folk. The number of people who Miguel touched that day and the number of people who will remember him are much more that those who will remember any of the speakers at technology forums where I have had the opportunity to speak or attend.

 

Miguel was different from my vision of the open source advocate. Probably because he was less of an advocate and more of a real programmer.

 

Miguel said that no they don't say that they are going to beat Microsoft or that Microsoft is going away or anything - which is normally common talk for OSI folk I have previously met. There is place for both he said. He said he has friends at Microsoft. He said that Dave Stutz is a good friend. We talked a little about Stallman and Free software. I asked him if he would be joining MS like Don Box offered and he said probably not. He would rather be doing his thing like this and be 'helping out the poorer countries'. He says they will keep on writing software, take good ideas wherever they find them and give it out as dirt cheap or free. There was this time when he said that 'they took out the GC and put in a toy GC in rotor and took out the JIT and put in a toy JIT in rotor - but the GC in Mono is your GC as much as its my GC' and he said that to Jani - 'its your as much as its mine and I would like to keep doing that'. There is this certain element of real sincerity which I find so missing in my work place and often at our technical seminars.

 

Free wheeling aside and sorry for all the typos and bad language in my writing, one thing that I probably miss from speakers and from many of our communities is that people hardly seem to be doing all that for themselves as much as for the community - I haven't seen anyone sit down and give all their time and energy to the community they are trying to foster. I don't see anyone on our side actually be there with the people and spread that sense of what they are doing - most of the audiences at our talks see us as speakers on podiums, rarely as people, we don't usually give them the room for that. I wish we could do that. And I wish that when we work on our user groups we can do it for the sense of community, rather than for the sakes of meeting numbers and budgets and revenue targets and stuff. I wish we all do this because we like our technology first - the Microsoft communities have never been able to do that the way these guys have. (This was probably rant, but reading this months later I feel that a lot of human touch is still missing in the communities. Somewhere the communities are built around a carrot culture and people who do things for carrots. Miguel has his carrots, but the way I saw his carrots were from a kind of passion that I personally feel in speakers I have known, myself being equally at fault. Something about what happened there that day felt like the spirit of those things I have thought about so much – hackerdom, the free hackers, the hacker ethic, mentor’s manifesto. Something is missing here and I am sure we can fix it because we have some extremely smart people who are so passionate about their technology)

 

I hope I have not tipped off any one by writing all this; this is probably something that could use some thought.

 

Cheers

Roshan

 

(Left to Right: Natt Friedman (Ximian/Novell of the Mono Project, cofounder of Ximian), Me, Miguel De Icaza (Ximian/Novell - author of Mono and other great feats of hackerdom, cofounder of Ximian), Gaurav Daga (Program Manager, Microsoft - Services for Unix Team), Pooja Malpani (CTS - programmer, Microsoft MVP .Net). This was taken at Linux Bangalore 2004, the annual Linux convention.)

 

 

(President’s quote put upon a hoarding at Linux Bangalore 2004)

 

 

 

This was recently posted on Miguel’s blog (there is more - go read the entry):
http://primates.ximian.com/~miguel/archive/2004/Apr-24.html

 

Jeff seems to like Cringley's statement of "The central point was that paying too much attention to Microsoft simply allows Microsoft to define the game. And when Microsoft gets to define the game, they ALWAYS win."

 

A nice statement, but nothing more than a nice statement, other than that, its all incorrect.

 

Microsoft has won in the past due to many factors, and none of them related to `Let them define the game', a couple from a list of many:

 

·         They leveraged their monopoly to break into new markets. The most discussed one is when they used brute force and anti-competitive strategies to get their products into new markets, but in some other cases they got fairly good adoption of their products with little or no effort: just bundle it with Windows: MSN messenger, Media Player.

 

·         Competitors were outmaneuvered or were incompetent (See HIgh Stakes No Prisoners).

 

·         People were sleeping at the wheel.

In 1993-1994, Linux had the promise of becoming the best desktop system. We had real multi-tasking, real 32-bit OS. Client and Server in the same system: Linux could be used as a server (file sharing, web serving), we could run DOS applications with dosemu. We had X11: could run applications remotely on a large server, and display on small machine. Linux quickly became a vibrant innovative community, and with virtual-desktops in our window managers, we could do things ten times as fast as Windows users!
TeX
was of course `much better than Windows, since it focuses on the content and the logical layout' and for those who did not like that, there was always the "Andrew" word processor. Tcl/Tk was as good as building apps with QuickBasic.

And then Microsoft released Windows 95.

 

·         A few years later, everyone is talking components: Netscape is putting IIOP on their client and server (ahead of their time, this later became popular as web-services on the browser); Xerox ILU; Bonobo; KParts; the Borland sponsored event to build a small component system that everyone agrees with; language bindings are at their top.

The concensus at that time? Whatever Microsoft is doing is just a thin layer on top of COM/DCOM/Windows DNA which to most of us means `same old, same old, we are innovating!'.

And then Microsoft comes up with .NET.

 

 

Maybe, sometimes, rarely, one man can change the world – or at least make a significant dent.

 

Tuesday, April 27, 2004 1:04:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [4]  | 
 Sunday, April 25, 2004

Iterators in Ruby (Part - 1)

Warming up to using Iterators (Part 2)
< I am yet to write a part 3 >
SICP, Fiber api and ITERATORS ! (Part 4)

 

I had a look at the implementation of iterators in C#. What follows is based on code generator I have seen on the C# Whidbey post PDC release. Things might have changed by now as things are moving to technology preview phase.

 

This is example code that is present in MSDN:

 

// yield-example.cs

using System;

using System.Collections;

public class List

{

    public static IEnumerable Power(int number, int exponent)

    {

        int counter =0;

        int result = 1;

        while(counter++ < exponent)

        {

            result = result * number;

            yield result;

        }

    }

 

    static void Main()

    {

        // Display powers of 2 up to the exponent 8:

        foreach(int i in Power(2, 8))

            Console.Write("{0} ", i);

    }

}

 

Notice the introduction of a nice little ‘yield’ keyword? The behavior of C# iterators in this context is a lot like ruby iterators that I have been talking about in previous articles. Knowing a little about the state management requirements for iterators and the fact that the CLR is stack based, how are iterators implemented in C#?

 

The implementation of iterators in C# is not driven by the CLR in any way, it is completely implemented in the language as a compiler construct.

 

Let me explain what the compiler tries to do – the compiler examines the function that does the yield

 

    public static IEnumerable Power(int number, int exponent)

    {

        int counter =0;

        int result = 1;

        while(counter++ < exponent)

        {

            result = result * number;

            yield result;

        }

    }

 

Lets just ignore the yield statement for now and look at the method as thought it contained only a loop. It would basically look like this:

 

    public static IEnumerable Power(int number, int exponent)

    {

        [initial code]

        while([loop condition])

        {

            [loop body]

        }

        [post loop code]

    }

 

This is then generated into a sequence of IL statement blocks that have the following jumps between them:

 

 

Now, what yield would require is that the method exit at each point a yield statement occurs. The next time the method is invoked, execution continues immediately past the yield statement with all variables preserving their values.

 

In the CLR, when a method returns its stack frame is torn down. So there is no way that the local variables can actually preserve state. The solution taken by the C# team is turn the method that implements the yield statement into a class.

 

Such a class would

 

·         Have all local variables of the method as members of the class

·         Have a special variable that hold the value that is being yielded.

·         Have a special variable to indicate where the method should continue from, the next time it is invoked.

 

When the caller of such a method runs and encounters the foreach loop that invokes the iterator an object of this class gets created. This object is maintained as long as the foreach lop is running. When the loop exits the object is disposed.

 

That’s how iterators are implemented in C#. :)

 

Now here are some details:

 

 

The method that implements the iterators generates not one but two classes. Both the classes are generated as nested/inner classes to the class that contains the method. The classes are named as
(method name)$(number )_IEnumerableImpl
(method name)$(number)_IEnumeratorImpl

 

I am not sure about the exact reasoning behind the generation of two classes. The earlier standard for writing enumerators in C# probably required, but from the standpoint of implementing iterators, I don’t understand the need.

 

The first of these, the IEnumerableImpl simply creates an instance of the second class and returns it to the caller.

 

The second class IEnumeratorImpl is the interesting one. This class has data members for all the local variables as well as our two special data members.

 

Compare the data members (the cyan colored diamond shapes) to the original  local variables of the method.

 

    public static IEnumerable Power(int number, int exponent)

    {

        int counter =0;

        int result = 1;

        while(counter++ < exponent)

        {

            result = result * number;

            yield result;

        }

    }

 

The parameters number and exponent are there as such and the local variables counter and result are there with some name mangling (I would expect this is to avoid clashes with duplicate names in nested scopes, though that is not allowed in C# (duh?)).

 

The two new members on the class are

·         $PC

·         $_current

 

$_current is the member that holds the yielded value. In the case of the above method, $_current holds the value of ‘result’. It is an ‘object’ type for there will be a nice boxing and gc overhead when moving around an int type – I don’t know why something was not done for special casing value types.

 

$PC is the interesting variable. Remember our little diagram above that showed execution through IL. In the case of the iterators, the method does not simply execute in a loop like shown there, but executes one iteration of the loop on each call. The $PC is the variable that keeps track of where the code should jump to, the next time the method is called. Understandably $PC is someone idea of program counter ;)

 

The code method called MoveNext() in the class actually does the work that the method power() originally did. This is what is look like in IL code.

 

 

Sorry I am not very good with diagrams, but if you look at it you will see that the code is simply built for repeated invocation. Each time according to $PC the code braches to a new location and executes. It then sets the value of $PC to a new location of entry before the function exits.

 

In C# the yielded value is assigned to the $_current member variable and the MoveNext() itself exits by returning a true or false. A true indicates that the method returned through a yield and the false indicates that the method has completed execution. Subsequent calls to the method, after it has returned false will simply cause the method to return false and the $_current will not be updated.

 

So how does the caller of an iterative method behave? In this case its the main. The  caller simply does the following –

 

Invoke Power$00000000__IEnumerableImpl. GetEnumerator() to get an instance of Power$00000000__IEnumeratorImpl

 

Invoke Power$00000000__IEnumeratorImpl.MoveNext()

 

If result is true, use invoke Power$00000000__IEnumeratorImpl.get_Current() which will return the $_current. The foreach loop will cause the MoveNext() to be invoked again after the reurned value is consumed.

 

If result is false, break out of foreach loop.

 

After the loop breaks out the instance of Power$00000000__IEnumeratorImpl is dispose and is available for garbage collection. 

 

I am looking forward to the beta preview to see f things have changed. There is a lot of rather redundant code generated by the compiler here that I have not mentioned. When you are reading IL you might want to skip over those parts.

 

Probably in the future the CLR will contain constructs that enable true iterators and closures. Present day processors don’t natively support such constructs and so implementation will have to be hacks on the C stack or using some kind of class-object mechanism like shown here.

 

As a foot note I would like to mention that the Python also implements iterators in a manner similar to C#. There the function that yields is also converted into a class that maintains state. I believe the MoveNext() equivalent in Python is simply next(). Python however raises an exception to signal end of iteration. C# uses a Boolean return value to indicate this.

 

If this topic holds your interest then I recommend reading:

 

Coroutines in C
by Simon Tatham

 

C# 2.0 Create Elegant Code with Anonymous Methods, Iterators, and Partial Classes
by Juval Lowy (MSDN Mag)

 

Charming Python: Iterators and simple generators - New constructs in Python 2.2
by David Mertz (developerWorks)

Sunday, April 25, 2004 6:16:33 AM (Eastern Standard Time, UTC-05:00)  #    Comments [7]  | 
 Friday, April 23, 2004

There is Dylan playing somewhere in my head, and some things feel crushed:

 

Though I know that evenin's empire has returned into sand,

Vanished from my hand,

Left me blindly here to stand but still not sleeping.

My weariness amazes me, I'm branded on my feet,

I have no one to meet

And the ancient empty street's too dead for dreaming.

(Tambourine Man)

 

Have you ever listened to Dylan? Actually heard the visions of what could have been move by you? Probably not, not many people like to listen.

 

Then take me disappearin' through the smoke rings of my mind,

Down the foggy ruins of time, far past the frozen leaves,

The haunted, frightened trees, out to the windy beach,

Far from the twisted reach of crazy sorrow.

Yes, to dance beneath the diamond sky with one hand waving free,

Silhouetted by the sea, circled by the circus sands,

With all memory and fate driven deep beneath the waves,

Let me forget about today until tomorrow.

 

Hey! Mr. Tambourine Man, play a song for me,

I'm not sleepy and there is no place I'm going to.

Hey! Mr. Tambourine Man, play a song for me,

In the jingle jangle morning I'll come followin' you.

 

Sometimes, the closed world of the bit and baud seems to be the only reality that matters and somewhere it cajoles you into believing in a certain brotherhood of those who seem to understand it. And then again sometimes not.

 

And do you listen to Simon and Garfunkel?

 

When you're down and out, When you're on the street
When evening falls so hard, I will comfort you
I'll take your part, when darkness comes
and pain is all around,
Like a bridge over troubled water, I will lay me down
Like a bridge over troubled water, I will lay me down

(Bridge over Troubled Waters)

Friday, April 23, 2004 2:17:13 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 
 Thursday, April 22, 2004

I downloaded and tried the new programming language Groovy today. In short groovy is like having Ruby on JVM. Maybe only better, because, it now has the power of the whole JVM to leverage. This is the homepage:

http://groovy.codehaus.org

 

 

The language is a stunner.

 

There is a lot of neat language design going on here.

http://wiki.codehaus.org/groovy/BlocksAndClosures

Imagine something like Ruby actually being available to code JSP, beans and what not in the Java world.

 

Being from the .Net background, I wish this was being done for the CLR. Imagine the power to the multi language support of the CLR brought into something like Ruby. For now I am content with gaping at features like this:

 

def counter(a)

{

      c = a;

      x = {c +=1; c};

      x

}

 

a_counter = counter(0)

b_counter = counter(20)

 

println(a_counter())

println(b_counter())

println(a_counter())

println(a_counter())

println(b_counter())

 

This actually works. Real closures!
If you are a lost C or VB soul, what is happening is that the function/method called counter() creates and returns a closure called x. A closure is a block of code that maintains state and scope based access to its variables. So closure x has the maintains state and has access to the variables of the method counter().

a_counter and b_counter are instance of the closure in the counter() method, that live after the invocations to the counter() method has exited. You can see that state is maintained between calls as the value of ‘c’ is incremented in each successive call.  

 

This is way ahead of languages like C# which are just grappling with their implementation of yield. This is of course not to blame the C# team, because admittedly the concept of programming with closures is yet to hit ‘the masses’

 

Groovy seems to do a whole pile of exciting things that Ruby can do

·         Closures

·         Iterators and Blocks

·         Regular expressions

·         Flexible collection types

·         Dynamic Method Invocations and types

I haven’t seen any mention of continuations, extendible classes, mixins and the like yet.