Sunday 29 September 2019

Functional Programming

I have to admit that I've never been into Functional Programming. I mean, I've used and loved for quite long some techniques related to Functional Programming, like: map, filter, forEach, closures, partial functions... but I've always used this as part of my OOP programming, I've never got into some other functional techniques and all the functional hype.

Last year I wrote this crappy post where as you can see I still could hardly see any particular use to function currying. Well, that has changed in the last days thanks to this article about currying and this article about lodash-fp.

The main element about currying that I had been missing is that a curried function can be invoked not just passing one argument at each call, but several arguments in one call (this is called Variadic Currying). I mean:

function myFunc(a, b, c){....}

//given a curried version of myFunc we can do:
myCurriedFunc(a)(b)(c);

//but also:
myCurriedFunc(a, b)(c);
myCurriedFunc(a)(b, c);
myCurriedFunc(a, b, c);

Not taking into account Variadic Currying, one could see no particular difference between Partial Function Application and Currying.

var _ = require('lodash');

function wrapTwice(wrapper, txt){
    return `${wrapper.repeat(2)} ${txt} ${wrapper.repeat(2)}`;
}

const wrapWithXPartial = _.partial(wrapTwice, "X");
const wrapWithXCurry = _.curry(wrapTwice)("X");

console.log(wrapWithXPartial("hi"));
//XX hi XX

console.log(wrapWithXCurry("hi"));
//XX hi XX

But Variadic Currying allows us to write this:

const curriedWrapTwice = _.curry(wrapTwice);
console.log(curriedWrapTwice("X", "hi"));
console.log(curriedWrapTwice("X")("hi"));

In the first invocation we are invoking the curried function just in the same was as we would invoke the original function. So we could just curry all our functions beforehand and then invoke them normally (with all the parameters) or in the curried style (one or x parameters at each time). Now you can wonder, "OK, and what for?". To answer this, you just have to read the second aforementioned article, and play around with lodash/fp. You'll also learn a piece of jargon "point-free programming" to throw around from time to time during an office coffee break.

By the way, the introductory paragraph:
The lodash/fp module promotes a more functional programming (FP) friendly style by exporting an instance of lodash with its methods wrapped to produce immutable auto-curried iteratee-first data-last methods.
could let you speechless (I've sent it to one friend to have fun with his reaction :-)... so a basic explanation:

  • auto-curried: What I mentioned above, the lodash/fp functions (map, filter...) have already been curried.
  • iteratee-first data-last: The parameters order with respect to their lodash counterparts has been inverted. We have lodash.map(collection, callback), and lodash/fp.map(callback, collection)

Friday 27 September 2019

Composing Functions

The other day somehow I ended reading this post and found an amazing piece of code:

const pipe = (...fns) => a => fns.reduce((b, f) => f(b), a);

Composing functions, that is, creating a function that chains several function calls passing the result of each function to the next... is nothing new, but the way this guy implements it using reduce quite caught my eye. Also, those 2 consecutive arrows puzzled me a bit. We have a function returning another function, but as both are written as arrows, the code seemed a bit strange to me at first... .

After this I was thinking about ways to compose functions provided by some commont javascript libraries. In lodash we have 2 options, _.chain and _.flow.

_.chain is not really a way to compose, but an alternative. When we want to compose functions provided by lodash, we can wrap our array/collection in a chainable object, and then chain method calls to that object. It's explained here.

let cities = [
    "Paris",
    null,
    "Toulouse",
    "Xixon",
    "",
    "Berlin"
];

result = _.chain(cities)
    .compact()
    .take(3)
    .reverse()
    .value();
//result = [ 'Xixon', 'Toulouse', 'Paris' ]

Rather than _.chain we can use _.flow, like this:

result = _.flow([
    _.compact,
    (ar) => _.take(ar, 3),
    _.reverse
])(cities);

Notice that with _.flow we are creating the composed function, that here we are invoking immediatelly, but that we could reuse for multiple calls. _.chain is just a one go approach. The other big difference is that _.chain is only valid when using lodash functions, while with _.flow we could be composing any sort of function.

The documentation of _.flow says something that at first read confused me a bit: "Creates a function that returns the result of invoking the given functions with the this binding of the created function". Well, when composing non-method functions most times they are not using "this" (as in the example above), so we don't care about it. But this is important when composing methods of a same object. Let's say I have this class:

class Formatter{
    constructor(repetitions){
        this.repetitions = repetitions;
    }

    format1(txt){
        return `${"[" .repeat(this.repetitions)} ${txt} ${"]" .repeat(this.repetitions)}`;
    }

    format2(txt){
        return `${"(" .repeat(this.repetitions)} ${txt} ${")" .repeat(this.repetitions)}`;
    }
}

If we compose the calls to format1 and format2 like this we will obviously be missing "this" in the method, and the result will be wrong:

let formatter = new Formatter(2);

let formatFn = _.flow([
    formatter.format1,
    formatter.format2
]);

console.log(formatFn("hi"));
// hi

With what we've read about "the binding of the created function", all we need to fix it is calling function.prototype.bind:

let boundFormatFn = formatFn.bind(formatter);
console.log(boundFormatFn("hi"));
// (( [[ hi ]] ))

If lodash were not providing this feature, we could just create additional functions to wrap each method call, or directly invoke bind on each method-function

let formatFn2 = _.flow([
    (st) => formatter.format1(st),
    (st) => formatter.format2(st)
]);
console.log(formatFn2("hi"));
//(( [[ hi ]] ))
console.log("------------------");

let formatFn3 = _.flow([
    formatter.format1.bind(formatter),
    formatter.format2.bind(formatter)
]);
console.log(formatFn3("hi"));
//(( [[ hi ]] ))

I've uploaded all the code to this gist

By the way, if you want to read some javascript programming way more interesting than this post, you can check this article about currying that I found recently.

Sunday 22 September 2019

Getting Used To

Humans have this amazing ability to adapt to our changing world. This is an essential evolutionary trait, and mainly, those who fail to adapt, fail to survive. But sometimes this capacity to adapt is not that good, sometimes adapting to changes is not the right option, the right option is fighting back those changes and reverting them.

In the last year France has shown me several examples of this kind of negative adaptation:

During the Gillet Jaunes crisis (that 'movement' that at the start was dubious, eclectic, incoherent and had none of my sympathy, and that soon became one more delirium of French far-left fascism, ultra-violence and reject for anyone that does not belong to their fucking sect) many shops (not just banks, also insurances, shops that would be worth to loot...) had to cover their windows with wood plaques to try to avoid the attacks. Initially this was done just for the day when the violent gatherings were due, Saturdays, but over time, as this yellow sickness was becoming chronic, businesses had no other choice that keeping these protections permanently to reduce costs. Overtime some of these wood plaques would get painted to try to make them attractive. There was a sense of normalization, as if having to cover windows shops from the attacks of some far-left parasites (and the hordes of your average muslim-banlieu-antiFrance-criminal (racaille) that joined them to enjoy the violence, insult, harass and attack normal citizens, burn stuff, and loot shops) was just something unavoidable, as if the state should not use as much force as necessary to immediately stop this madness.

Months ago I read a report (not sure if in Le Monde or Liberation, for the most part I no longer read those leftist pamphlets other than if redirected there from some other site making fun of their islamo-collaborationist articles), that quite shocked me. It explained the 'astuces' (tricks) that a group of young girls living in 'banlieu parisien' (the outskirts, somewhere outside the peripherique - 20 arrondissements) had to use when they wanted to go to Paris by public transport to enjoy a night out. As it was not a good idea to wear a nice, a bit revealing maybe, dress in a wagon that could be infected by undesirables (do I need to explain to what "culture" do 90% of them belong to...?), the girls would go dressed normally with their night clothes in a bag to get changed later on in the flat of one friend living in Paris proper. The crazy thing is that this article was not denouncing this situation, this lack of freedom, as something unacceptable, but just talking about it as a normal, almost cool, situation. This thing of the girls getting changed in one friend flat is not new, but I associate it with the dark times of Franco's dictatorship in Spain, a mechanism to avoid the anger of conservative society, but now, in XXI century France (well, I can easily imagine the same situation in Brussels...) this has become normal.

If you watch this documentary about Saint Denis, that city in the Paris Metropolitan area that hosts the basilica where many French kings are buried and that has now become a Muslim enclave (well, good part of the Seine Saint Denis department, le 93, is a Muslim enclave...), you'll find many shockingly disturbing things, but there's something that particularly caught my attention. Obviously this city is way much cheaper than Paris, and there are some rather beautiful hausmannian buildings (I can say the same for Montreuil, one city in the same department (province) where I've spent some time), so some Parisians are willing to move there to enjoy a much better property. We follow the real state agent walking a potential client along the city's main street, and the conversation is interesting. The client notes that them 'French people of European descent' are a minority in the place, but seems no particularly concerned. Then the agent gives her the 3 main advices for living in the city: never pull out your smartphone on the street, always hold your bag tightly and on the front side, and when driving always make sure your doors are well closed and never put your bag on a seat. Again, the client does not seem particularly surprised, and we learn she will end up buying a property and moving to St Denis. From this to having to live in closed, protected communities like in South Africa, Mexico... there are just a few steps... If you think I'm going too far... there's another fact revealed by the documentary that absolutely goes in this line. In the last decade many companies have set offices in Saint Denis, leveraging the low prices in an extensive area of industrial ruins that has been turned into offices. Apart from the huge security measures adopted to control the access to the premises, many companies have had to put in place a system of mini-buses (navettes) so that those employees going to work by public transport can be driven safely from the Metro station to the Offices and back.

Saturday 21 September 2019

Amerika Square

I think Amerika Square is the second Greek film that I've watched in my life (I won't consider Costas Gravas films as Greek, he's French-Greek and all his studies and career has gone by in France). Amerika Square tells a tragic, very present story, with a dark sense of humor. Two friends in their 40's deal in a totally opposite way with the tragic consequences of the refugee crisis in their neighborhood in Athenas.

While the film takes a leftist stance, the way it portraits the nationalistic-xenophobic character is not totally absurd or sectarian, on the contrary, it makes you understand (understanding is not the same as agreeing) why he has ended up thinking like that. It shows the drama of those that have lost their land and references by being forced to flee their home, but also the drama of those that because of the economical crisis and the changes to their neighborhood brought about by the massive arrival of "the others", no longer feel at home. The element in the psyche of this character that is senseless to me is that he seems to profess the same level of hate for all immigrants, regardless of whether they are Polish Christians, Peaceful Asian guys, or Muslims. I think it's quite unlikely to find an attitude like that save in the most extreme far-right bastards.

A very human film that makes you understand the desperation on both sides. This understanding stems from the fact that on both sides the film shows us the good ones. The main immigrants, save for the Russian maphia, are nice people that just want a chance for a better life (they are not Islamist scum or social aid parasites). The same goes for the 'xenophobe', he's not an educated motherfucker with some crazy theory of race and ancestry, but a poor guy that can not find a job, suffers seeing the degradation of his neighborhood and longs for the peaceful, cohesive society of his childhood.

The other Greek film that I'm aware of having watched, Plato's Academy also had immigration, economical crisis and xenophobia as its main topic. I watched that film in FIC Xixon 2010, so we were in the middle of the huge crisis caused by the economy crash of 2008, but quite before the migrant crisis, and a bit before the rise of Golden Dawn, the nazi scum party. Already at that time ordinary Greeks were fucked by their poor economy and some of them were angry to 'the others', the Albanians mainly.