Tuesday, 27 April 2010

Access to closure variables

Something that I had thought sometimes that could be useful regarding closures (that is, functions with state) is having access to the "enclosed variables" of the closure from outside it.
I usually call these variables "free variables of the closure" but it seems that the most accurate name is upvalues. Well, anyway, the question is, is it possible to have access to these values?

  • I think it's not possible in JavaScript.

  • I think to remember that it was possible in Python (I think somewhere in the function object or the code object there was a free_vars property).

  • I've tested that it is possible in C#.

The way I've found to get access to these variables fully depends on how the C# compiler implements closures, I guess this is not part of any specification. So, it's just something that anyone can check with Reflector but could change in future versions.

Let's say we have a method Formatter that formats some strings and we'd like to add some state info to the method, e.g. how many times it has been called. Well, it's easy, we just enclose the method into a closure:

   1:  Func<Func<string, string, string>> counterClosureGenerator = delegate()

   2:              {

   3:                  int counter = 0;

   4:                  return delegate(string st1, string st2)

   5:                  {

   6:                      counter++;

   7:                      return Formatter(st1, st2);

   8:                  };

   9:              };


  11:  Func<string, string, string> enclosedFormatter = counterClosureGenerator();

where enclosedFormatter is the closure and counter stores the number of times it's been called.

Unfortunately we can't do something like: enclosedFormatter.FreeVars["counter"] or anything like that... so what?

Well, if we know a bit about how closures are implemented, we should be aware that the anonymous method that is the base for the closure is created as a normal method inside a normal class (with some esoteric name like <>c__DisplayClass3), that will contain (as public fields) those free variables used by the closure.

With all this in mind, and with a bit of Reflection (Introspection) magic, getting access to one of those free variables is as easy as this:

   1:  class ClosureHelper

   2:  {

   3:      public static object GetValue(Delegate deleg, string varName)

   4:      {

   5:          FieldInfo field = deleg.Target.GetType().GetField(varName);

   6:          return field.GetValue(deleg.Target);

   7:      }


   9:      public static void SetValue(Delegate deleg, string varName, object value)

  10:      {

  11:          FieldInfo field = deleg.Target.GetType().GetField(varName);

  12:          field.SetValue(deleg.Target, value);

  13:      }

  14:  }

OK, sure this is not much useful, but it was fun to write about it. You can download the source here.

Monday, 26 April 2010

Katalin Varga

Absolutely brilliant debut film for this British director: Peter Strickland.

A total drama takes place in present day rural Romania, where a woman searching for vengeance gets into an spiral of pain affecting everyone involved. Trying to heal her hurts all she gets is worsening them and hurting others...

This is the kind of independent film that my subconscious links to FIC Xixón, so it felt a bit strange to watch it from my sofa. It has many of the good ingredients that I associate to independent films: long shots with an aesthetic aim that give you some extra time to analyze what's happennig and what could happen next, blurred images, blurred images of cars driving at night... different elements with an almost hypnotic effect (though the most hypnotic element in the film is the savage beauty of the main female character).

For an urban rat like me one of the most moving points of the film is how beautifully it depicts life in the remote countryside of remote eastern Europe...
Only a few elements (superflous to the story) make you realize that this is happening in present time and not 2 centuries ago.

A total must-see film for anyone interested in beautifully sad stories.

Wednesday, 14 April 2010

Extension Methods aka Methodize

Thought lately I've been a happy jQuery user, Prototype.js is the first "2.0" javascript library that I used, and I like to keep an eye on what the fantastic team of developers behind it are up to.
Far beyond the Ajax, Dom, Events... features, what is really interesting to me from prototype.js is all the "language extension" stuff. What I mean with this are methods like Class.create, Object.extend, Function.bind... that take advantage of the incredible dynamism of javascript to shape it into a different beast (this said, I'd like to note that I very much appreciate the prototype-based paradigm and I don't ever feel the need to simulate the class-based paradigm in javascript).

One method that called my attention today is Function.methodize. At first it seemed a bit strange to me.
Function.bind seems like an indispensable addition that all of us had wished before it got implemented, Function.curry (I think Function.partial should be a better name, but the currying vs partial debate [1], [2] is a bit confusing to me) sounds familiar from other "functional friendly" languages...
So, what about this Function.methodize?
Well, the sample makes it clear. You have a function that expects x elements and would like to be able to paste it to an object and call it via that object (in a "method invocation style") with that object acting as the first argument.

Note here that the need for methodize comes from how "this" works in javascript. The "this" concept in javascript is more in line with languages like C# or java than with languages like python. In these languages "this" is a special item, the object through which the method was called, it seems rather reasonable for static languages. In python we don't have the "this" idea (the usage of "self" in methods is just a convention), at first it would seem like there's not a so clear distinction between functions and methods, you just declare functions, if declared at the module level, they expect you to type the first parameter in the invocation, when defined at the class level, the first parameter is passed by the runtime using the "invokator object" (well, all this is rather more complex, in fact in python we have function objects, method objects, bound and unbound, Descriptors magic... and it's a long time that I don't touch python).
Anyway, for a so "open" language like javascript maybe the python approach would have been better.

If you think it a bit more, you realize that methodize is just the same as C#'s Extension methods. You've got a static method and would like to call it via an object that will work as the first parameter...
Also in C# this gives us unprecedented extensibility, adding Traits to the game (the article says Mixins, but I think to remember having read somewhere that Mixins can have state and Traits can't... so in that case it should say Traits).
It's interesting to see how some simple compiler magic (if not in the class, just search the method in the list of extension methods with that class marked as this) can add much power to a language.

Sunday, 11 April 2010

The slippery slope of evil

One more excellent documentary in Redes: La pendiente resbaladiza de la maldad (sorry, it's only in Spanish).
This time Eduard Punset interviews Philip Zimbardo. In the early seventies Zimbardo conducted one of the most revealing experiments ever done on Human behaviour, the Stanford prison study. In short, he selected some volunteers among Stanford students and tried to recreate with them life in prison. Students were divided in two groups randomly, one group would represent prisoners and one group would represent the guards. In a few days everything was out of control, "guards" had adopted their role so deeply that were almost torturing the "prisoners". Even Zimbardo himself had entered the game so much that was unable to realize how grotesque the whole thing had turned... At first, prisoners showed rebellious and questioned the authority of the guards, but once they started to feel stressed by the situation, they ended up accepting their role of "oppressed". One important point of the experiment is that these early 70's Californian students were mainly part of the dominant youth culture of those days, that is, anti-war, anti-authority, political awareness...

Different conclusions can be drawn from this experiment, I quite like this found in wikipedia:
The experiment's result has been argued to demonstrate the impressionability and obedience of people when provided with a legitimizing ideology and social and institutional support. It is also used to illustrate cognitive dissonance theory and the power of authority.
I would add that it demonstrates how easy it's for humans to accept a given role and (over)act according to it, that is, act according to what society, bosses... expect from us, and not according to our inner desires...

The results of the experiment are in line with those of the also famous Milgram experiment. In this second case "oppressors" were obeying direct orders, not just doing what should be expected from them, but anyway, conclusion seems similar to me: people like to obey, to follow a given path instead of tracing their own... Accepting authority is a comfortable way for many people, as it releases them from moral dilemmas concerning their actions, if you're just following orders, it would be the Master who should reflect about the morality of the actions he's commanding, but not you. So, in the end, we're selling our souls and free will for a bit of "comfort".

There's another related experiment, The Third Wave that tries to demonstrate the appeal of fascism. Some months ago I watched a rather good German film inspired by that experiment, "The Wave".

Saturday, 3 April 2010

Fruitful weekend

Well, the title might be slightly misleading. Neither did I have a weekend break (here in Asturies our few low cost flying options mainly mean losing a full day each way), nor an intense social life, nor a "sex, fruit juices and punk" weekend... I just happened to watch some great documentaries!

  • Ice Age Columbus, who were the first Americans touches the topic of when and from where did the first Homo Sapines reach America. The most commonly accepted theory says that Sapiens got to America from Asia, crossing the Bering Strait (that at that time was not a strait, but a mass land called Beringia) about 20000 years ago, this is the Clovis First theory. This Docudrama (not sure if this classification is correct, it's one of those documentaries that uses actors and uses a fictitious story to help represent a feasible reality) tells us a different story that has been gaining supporters in the last years, the Solutrean Hypothesis. In short, this theory says that it were people from Southern France or the Cantabrian Coast (hey, those could be my ancestors!) who first reached North America, using the Ice bridge that at that time joined Southern France with North America. In this Ice Age period the sea level was rather lower than now, so good part of the places where these people could settle are covered by the sea at the present time and we can't search for traces of their presence there. Anyway, some traces have been found, like the fluted stone tool found in Cactus Hill.
    Rather interesting to whet your appetite and do some more investigation.

  • Quest for Noah's flood by National Geographic is another interesting one. It tells us how the ancient flood story that is common to many world cultures (Noah's flood for Christians) could be based on real facts that happened 7000 years ago in what we now call Black Sea. Another interesting thing I learned from the documentary is that most of its water volume is anoxic and lifeless (over 90% of the deeper Black Sea volume is anoxic water). The Black Sea happens to be the world’s largest meromictic basin. Well, they don't mention this word in the documentary and I hadn't read it before until I read the wikipedia article, but it's the name for a phenomenon that I already knew, but I mainly related to lakes, when the upper and lower water layers do never intermix. In Volcanic lakes this can make the lower layer to accumulate CO2 and in the end it could lead to a catastrophe (like the one in Lake Nyos). There are some documentaries dealing with this topic, like "Naked Science: Killer Lakes" and "MegaDisasters: Methane Explosion".

  • The third documentary of the weekend was this one about current Israeli society (unfortunately it's only in Spanish). This is not one of those constant reminders of how good the Palestinians are and how evil the Israelis are... you know, that proislamic retoric so popular among many westerns (from neonazi scum to extreme left)... frankly I'm more interested in how the normal people in Israel (secular, moderate Jewish, moderate Muslims...) live, trying to survive between crazy fundamentalist Jewish and crazy fundamentalist Muslims. This documentary deals a bit with that, the good things of Israel:
    the ideas underlying the first Kibbutzs, the incredible scientific development, the normal status of the gay population...
    and the bad ones: the discrimination that those Palestinians living in Israel and contributing to the normal work of the society still have to suffer, the disgusting orthodox Jews, the Jewish settlements beyond the acceptable borders...