Tuesday 25 February 2014

Prisoners

I found myself with this film playing on my laptop with quite little information about it and unclear expectations. It was just one of the titles that showed up in some of my typical early year seachs: "Best Thriller films 201X", "Best Drama films 201X", "Best Horror films 201X"...

It didn't start too well. The archetypical American family: religious, living in one of those neighbourhoods of single-family houses where you need your car even to go to buy the newspaper, with a father (a Hugh Jackman very concerned about getting ready for the end of the world) that has just taught his teenager son (very concerned about how to buy his first car) to hunt a deer... Well, you know that I'm a proud European (even more now that I'm living in France), so the "American Way of Life" is almost that alien and disturbing to me as the "Saudi Way of Life". OK, I have to say that this family are close friends with an AfroAmerican family, which is not a so "American thing", as however much they now have a black president (a black president that continues to invade countries under the pretext of "peace and democracy" as aggressively as his "WASP" predecessors did), my understanding is that both communities continue to be seriously disconnected (and what to say of the "Brown" (latin) community...) Well, enough hate for the USA for today, let's focus on the film.

So, both families come together for Thanksgiving day (yet more American stuff...) and during the afternoon their 2 little girls get abducted. Not satisfied with how the police is carrying out the investigation, one of the 2 fathers (Hugh Jackman) decides to put matters in his own hands, but the whole thing goes out of control and the victim turns into monster. I won't give more details, just will say that as the film draws on, what could have been just one more entertaining film turns into an excellent one. The plot develops masterfully and unexpectedly, facing us with the moral struggles of 2 tortuous souls.

Once finished I felt prompted to check what other films this director had worked on, finding out that this man is the genius that directed Incendies and Polytechnique 2 absolutely breathtaking works. Indeed, one can find some common ground between Prisoners and Incendies, being the religious factor the most notable to me. From the "War for God" in Incendies (that sequence when a Christian Lebanese militia executes a group of innocent muslims and we can see an image of Virgin Mary glued on the machine gun of one of the executioners is one of the best representations of human misery that I've come across in a long while), to the "War against God" of the murderers in Prisoners, intending to make people to lose their faith through the exposure to a horror and injustice that a benevolent God would never allow.

The DVD release of this film was announced on many French kiosks last week. In the advertisement they compared it to Seven. Well, I wouldn't have come up with such relation on my own, but indeed it's not misguided, though Seven remains at an upper level that very few films can reach.

Saturday 15 February 2014

Perl is Cool 2, Reflection

Perl sports some excellent reflection capabilities, indeed it does not need a Reflection API as Reflection is built into the Language itself. Let's take a fast look at some of these features:

eval

Same as JavaScript, Perl provides an eval function that allows for the compilation of new code at runtime. You could be tempted to use it in many occasions (creating new Objects, accessing Methods or Data Fields known at runtime), but most times this is unnecessary and you can use a more straightforward approach.

Get Object Type

You can get the type of an object (the Package used to bless a reference) with ref.

Object Creation

Notice that ref returns a string (in contrast with .Net or Java, where .GetType or .getClass return an instance of Type or Class respectively, a special type that exists just for that, representing types). Being just a string could seem to pose some limitations, but it doesn't, cause perl allows you to use a string to reference a package/class and invoke methods on it. This means that you can create objects based on a string provided at runtime:

my $type = "Person";
$type->New("Iyan");

If you're writing Old School Object Oriented Perl you're using just that in your constructors to bless your references:

sub Person{
my ($class, $name) = @_;
my $self = {
name => $name
};
bless $self, $class;
return $self;
...
Method Invokation

Likewise, you can use a string to invoke a method

my $methodName = "SayHi";
$p1->$methodName();

Obviously you can combine the 2 features above, doing something like this:

my $class = "Person";
say $class->New("Anton")->$method();
Check whether an object has a method
You can do this directly on your "class instances" by means of UNIVERSAL::can , or by checking if the corresponding module contains that function:
say "p1 " . ($p1->can("SayHi") ? "CAN" : "CAN NOT") . " sayHi";

say "Person " .  (defined(Person::SayHi) ? "CAN" : "CAN NOT") . " SayHi";
Get Current Method Name
You can use the caller function to traverse the current stack. It returns an array of strings, one of the most useful uses is doing a print (caller(0))[3]; to get the name of the currently executing function.

Get Package Name
You can get the name of the current module with __PACKAGE__

Get File Name
You can get the path of the current module with __FILE__

Expand your objects
Once you've learnt that the minimalistic (but incredibly powerful) support for OOP in Perl revolves above blessing hash references (yes, I know you can bless other objects, but it's pretty uncommon), you can draw similarities with JavaScript, and start to think of your Perl objects as objects that can be expanded at will with new fields and methods. Well, this is partially correct.

You'll have no problem in adding new data fields to your instances:
my $p1 = Person->New(); #where Person::New does not create any "color" property
$p1->{color} = "red";
but adding a method is a different story. This is cause the method look up mechanism in Perl is pretty different from JavaScript's one. Invoking a method in JavaScript will mean retrieving the corresponding function referenced by that object property (directly or through the prototype chain) and calling it with the corresponding "dynamic this". In Perl, when a method invokation is done on an object (a blessed reference), the interpreter will search that function in the package that was used to bless that object and will invoke it passing over to it the object as first argument.
So If you set an object property to a function reference, invoking it as if it were a normal method will fail (with an error like this: Can't locate object method "SayBye" via package "Person" , as that function is not in the Package itself, but you can use a sort of workaround:
#adding a method to an object
$p1->{SayBye} = sub{
	my $self = shift;
	return $self->{"name"} . " is saying Bye";
};

#the method look up does not work, as it's trying to find the method in the Person package, and it's not there
#Runtime error: Can't locate object method "SayBye" via package "Person" 
#print $p1->SayBye() . "\n";

#so we have to do it this way, by accessing the coderef in the object
print $p1->{SayBye}->($p1) . "\n";

I think we could do the above workaround much more elegant by means of AUTOLOAD, but I haven't had time yet to fiddle with it.

Monday 10 February 2014

Objects are Not Dictionaries

First time I found out that ES6 was adding maps to JavaScript it seemed odd to me, as at that time I used to think about JavaScript objects as dictionaries/maps (you can add/delete/access items in them through string keys), but this is not true (or at least it's just partially true). I've been reminded of this fact while confirming that likewise Perl Hashes can only store strings as keys (they'll stringify any object that you use as a key).

So, first of all, JavaScript objects can only use strings as keys (compare this with .Net Dictionary<K,V> or Java's Map<K,V>, where K can be any type of object). This is the main issue addressed by ES6 Maps.

Second, as nicely explained here, a normal object already contains a number of "keys" inherited from Object.prototype, so that can pose a problem if the user of the object/dictionary attempts to use those keys as normal keys. There's a simple solution for that in ES5 (explained here), use for your dictionaries Objects with a null [[Prototype]], by means of Object.create(null);

By the way, posting a link to the ES5 and ES6 (draf) specifications adds some points to anyone's geek status :-D

Saturday 1 February 2014

Perl is Cool 1: First Class Functions

Last months at work I've been doing Perl, Perl and more Perl, and honestly, it sounds pretty much better than you could think. I already gave my first impressions here. The language is full of idioms that I don't like at all, as on one side they are not particularly useful and on the other side they're so alien to any other language that make code pretty hard to understand. Nevertheless, it has most (and sometimes much more, ie, multiple inheritance and AUTOLOAD) of the features that you would expect in a modern, decent language. This is the first (and very basic) installment in (maybe) a series of entries about "The Good Parts" of Perl.

As already mentioned in that previous entry, JavaScript draws much influence from Perl, and Functions (yes, I know the Perl word for this is "subroutines", but I'll call them functions) is one of the clear areas were any JavaScripter will feel mainly at home. Perl sports First Class Functions (that is, you can create Higher Order Functions), meaning that you can pass functions around and create and return them.

We have Named functions

sub doBeep{
 my ($name) = @_;
 say "doBeep: " . $name;
}

We can pass these functions to other functions, the only thing to take into account is that you don't pass around functions, but references to functions (yeah, having to waste brain cycles in thinking whether something is "a something" or "a reference to that something" stinks to old, awful C++). So you'll have to do this:

#I have a reference to a function here
my $doBeepRef = \&doBeep;
testCallback($doBeepRef);

As we're passing a reference to a function, you'll have to dereference it to invoke it, which can be done in these 2 ways:

sub testCallback{
 my $callback = shift;
 print "testing callback\n";
 #so to invoke it I have to dereference it, either this way:
 $callback->("yup");
 #or this way:
 &{$callback}("yup");
}

We also have anonymous functions. When declared we already get a reference to a function. We can declare them in an assignment, as a parameter or as a return:

my $callback = sub{ 
 #whatever
};

testCallback(sub{
 #whatever
});

sub functionFactory{
 return sub{
  #whatever
 };
)

Anonymous functions are particularly useful cause Perl has Closures:

sub wrapString{
 my ($wrapper, $str) = @_;
 return $wrapper . $str . $wrapper;
}

sub wrapperFactory{
 my $wrapper = shift;
 return sub{
  return wrapString($wrapper, @_);
 }
}

my $underscoreWrapper = wrapperFactory('_');
print $underscoreWrapper->("hi") . "\n";

The normal use of closures in Perl is the same as in other languages, but I don't know how they are implemented internally (in JavaScript you have the [[scope]] thing, in C# and Groovy the compiler creates extra classes under the covers, so I'm not sure about how they behave in more complex scenarios. This document explains some oddities.

Update, 2014-02-07 I forgot to mention that Perl has the equivalent to JavaScript's Immediately invoked function expressions (IIFEs). Let's see an example creating a closure:

my $printWithCounter = sub{
	my $counter = 0;
	return sub{
		print "printing for time " . $counter++ . "\n";
	}
}->();

for my $i (1..5){
	$printWithCounter->();
}