TypeScript is actually JavaScript and one still has to be careful

TypeScript, although very promising language, does not solve fundamental JavaScript’s issue (feature?) with “this” property binding. TypeScript can lead to unfortunate errors since it is heavily used by people coming from C#/Java communities, who bring coding patterns with them. Let’s have a look at code example from TypeScript playground:

Now, lets make slight change to the last two code lines:

This happens because greet() method references this and when you make a call of greet() not on the object, this gets bound to the global scope. It’s really unfortunate that one can so easily destroy TypeScript object’s integrity. In C# this example would work just fine and therefore C# developers should be extra careful to avoid this pitfall:

Now, even knowing all rules of this binding (take a look at this article if you are not aware of these rules), I was caught when I was coding in TypeScript class for Angular 2 framework:

See how updateClock local function starts accessing Timer properties via this? Seriously, I was debugging this code full of surprise trying to understand why am I getting an error. And the reason was that updateClock() is invoked without binding to any object which meant binding to the global scope again.

Conclusion: TypeScript is great, but guys, don’t relax, remember you are still coding in JavaScript, not C# or Java. And probably avoid using classes and this altogether.

Facebooktwittergoogle_pluslinkedinmailFacebooktwittergoogle_pluslinkedinmail

Learning from APL: item by item function application

There are many old cool languages in the world which brought absolutely new ideas into programming. One of them is APL and its main idea was to build programs as array processing pipelines. And it is amazing how many pretty complex problems can be solved in APL very easily and expressively using just array processing. Modern programming languages all get features which enable us building programs which almost completely consist of array processing pipelines. Just look at LINQ and how it transformed the way how C# is written today. However, we still write loops and conditionals as soon as we encounter a slightly different problem then filtering and mapping. Let’s learn a bit from APL.

In APL every function is applied to the parameter array item by item:

2 5 7 + 3 6 1 yields 5 11 8

What would C# developer do if he wanted to calculate such a sum? Well, who knows, but from my experience many would resort to the loop. However, LINQ has a special function which will help to do item by item computation. And this function is Zip:

new[] { 2, 5, 7 }.Zip(new[] { 3, 6, 1 }, (x, y) => x + y) // yields 5 11 8;

Now, here is another, more realistic problem. You have a turnover in million of dollars of some company over a period of 12 months: 56 59 67 64 60 61 68 73 78 75 81 84. Can you calculate the company growth in percent in every month starting from the second month? No loops! No conditionals! Only using array processing pipeline. Stop reading, go and try to do it in your language. Result should be 5.36 13.56 ¯4.48 ¯6.25 1.67 11.48 7.35 6.85 ¯3.85 8 3.70.

I will not show you APL solution, to understand it you will need to know APL. But I will show how to solve the problem APL way in C# and JavaScript here.

Let’s start with C# (I have implemented few LINQ extensions for readability purposes):

Now let’s have a look at possible JavaScript implementation (I use lodashjs library here to organize array processing pipeline, not surprisingly there is also a zipping function named zipWith. In general, every functional language or library has some kind of zipping function)

Note that in both examples growth is calculated in very functional style. No loops, no conditionals, no variables are used. Computation is organized as a sequence of data array transformations. Very similar to the pipe & filters design pattern. Here every filter is a pure function, no side effects, no procedural code. Hence, in this article, we have taken the first lesson from APL and this lesson leads us closer to the purely functional programming.

Facebooktwittergoogle_pluslinkedinmailFacebooktwittergoogle_pluslinkedinmail

Configuring function call

In programming, everywhere in the code we use procedural abstractions in the form of function/procedure or method (in object-oriented programming).  These procedural abstractions (later in the article I will call them just functions) usually have parameters. It is interesting that if you fix one or more parameters to some particular value, the function can acquire additional meaning and can be used as a dedicated function with a separate name.  For example, consider function add(x,y).  When you take the first parameter and fix it to some number, for example, x=1, then this function can acquire new meaning – incrementing. Function add(1, y) now can be named increment(y). The example is a bit unpractical, but this is done for the sake of simplicity. Although developers don’t pay much attention to such situations much, they often have to make design decision: what parameter to fix and what should be the name of the new function. After this decision is made, there are several techniques which can be used to implement this decision.

The first one is classical: using the object or just plain parameter passing. (in object-oriented programming sense). When the object is constructed, the value to be fixed is passed into the constructor. Here is C# implementation of incrementing functionality based on addition function:

In some sense, it is not the most elegant solution because Of method actually takes increment parameter implicitly. It could be done even in C by explicit passing increment parameter to Of function: Of(increment,5). It is not elegant because 1) caller should always know about increment parameter and apply it to Of function; 2) new semantics is conveyed through parameter name, that is “increment” which is the name of the parameter, not function. The function itself has a unexpressive name.

Much more interesting way to do the same thing is using closure. The closure is basically a function that has a special ability to access other variables local to the scope it was created in. Here is implementation of increment using closures in C# (yes, this great language actually support closures!):

If syntaxis of Evaluator method looks weird to you, it’s just C#6 feature – expression-bodied function. In this snippet, Evaluator takes argument x and then it looks like evaluation function gets called with an x parameter. But it is not what happens. In fact whole function y => evaluate(x, y) returns as a result and x is “closed” in this function, that is when Evaluator function returns, x variable is not destroyed as it normally would, it continues its life incide y => evaluate(x, y). That is why increment(5) gives 6. The parameter x still lives in object referenced by increment variable. Sounds cool? Not as cool as the next method!

Even more interesting, terse and elegant way to implement increment is using currying. Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. For example evaluation of function, add(x,y) can be considered as two steps process. 1) The parameter x is applied to add which yields another function, which takes one argument. The value of x is “embedded” inside returned function in the same way as it was done with closures. 2) Parameter y is applied to the just returned function which yields the sum of x and y. Unfortunately, C# does not support currying and hardly ever will. Therefore here is implementation of increment with currying in F#:

So, everything you do is “let increment = add 1”! It is hard to imagine something even more expressive than that.

It is not that currying is impossible to do in C# at all. You still can do some ugly hacks, the question, of course, is whether you want to do it. But who knows, maybe one day you will need it:

JavaScript is an interesting language. It does not support much stuff, but it is so flexible and dynamic, that one can introduce lacking concepts into the language using libraries. There is a very nice library, named Underscore.js, which facilitates very much functional programming in JavaScript. See how it is relatively easy to do currying in JavaScript using Underscore.js (actually I demonstrate partial function application here, but the subtle difference between partial function application and currying is off topic):

If it is hard to you to wrap your head around all these concepts, check out some course on functional programming. Sooner or later in your career you will encounter them again.
I can recommend a very nice introductory course from Delft university on edX.

Facebooktwittergoogle_pluslinkedinmailFacebooktwittergoogle_pluslinkedinmail