Sunday 29 May 2016

Yo! - I'm a Lambda.

I've just been reading up on the new JavaScript/ECMAScript 6 features and in particular the new fat-arrow syntax for lambdas.

It's funny, but whenever I see this syntax () => { } in C# code, my mind always shouts to me "Yo!! - I'm a Lambda". - Okay, I understand that might sound weird... It is weird and I don't know how to stop it!

Let me explain!

What I mean is, as programmers, when we read code our brain automatically identifies the cryptic string of characters and converts them to a mental model of what the code will do on the fly. For example, when scanning code, if you come across a for or while keyword your brain automatically tells you: "oh... there's a loop coming". If you see an if you automatically know there is a condition and a branch coming.

This happens instantaneously without fore-thought. It's like words on a poster. Your mind reads the words even if you're not interested in what the poster is advertising. In fact, put anything in front of yourself with words and your mind just reads it without asking you! It just happens!

In C#, whenever I see the the following syntax () -> {}, my mind always shouts to me "Yo!! - I'm a Lambda" because when I was learning the arrow syntax I engraved that sentence into my sub-conscious. And now... I can't shake it!!

So there I was, reading the new JavaScript syntax for lambda's and it happened again! This is when I thought it would be interesting to write a blog post on lambda's and compare the different lambda syntax's from various languages. You know, to see if my mind would play this phrase across languages.

Quick n Dirty Overview of Lambda's


Way back in the day, when I first saw a lambda I remember thinking, "what the smeg is that?" - It was weird looking code like this: x => { return x + 1; }. I didn't know what the X was doing on the left hand side. It just looked funny... Turns out, it is a lambda!

This is how you read a lambda expression:
  • Everything to the LEFT of the arrow is the function parameters.
  • Everything to the RIGHT of the arrow is the function body.
Remember good old-fashioned functions like this:
int AddOne(int x)
{
   return x + 1;
}
To write that as a lambda it becomes:
(int x) => { return x + 1; }
Notice above, that you can see the outline of the function still. You can still see the function takes an int as a parameter named x. Okay, its on one-line, and the name has gone but the outline is still there. The additional punctuation/syntax that's been added is the => which is where my "Yo!! - I'm a Lambda" gets triggered.

Turns out though that we can simplify this even more. If the compiler can determine the type that's passed in, you don’t need to put it there. So it becomes:
(x) => { return x + 1; }
Now, as this function only takes 1 parameter it turns out you can also leave out the parenthesis which gives you:
x => { return x + 1; }
Finally, you can simplify it even more and leave out the return statement (and remove the parenthesis). Then it becomes:
x => x + 1
This is the transformation:
// From this traditional Function
int AddOne(int x)
{
   return x + 1;
}

// ...to this Lambda expression!
x => x + 1

That's all good and easy to understand but when I used to see the code below it used to throw me.
var sum = () => 1 + 2;
It was the empty parenthesis that did it. But that's just a lambda expression that takes zero parameters and returns the sum of 1 + 2. But it looks odd.

Want to see what lambdas look like in other languages? Turns out, so did I. Read on!

C# Lambda Syntax

Okay, we already know what the C# code looks like. Below is the AddOne function as a lambda expression.

class Program
{
    public delegate int AddOne(int value);

    static void Main(string[] args)
    {
        AddOne lambdaFunc = (int someVar) => { return someVar + 1; };

        lambdaFunc(2);
    }
}

You can test this out with the online C# compiler here: http://csharppad.com/

JavaScript Lambda Syntax

As I mentioned earlier, it was whilst reading up on JavaScript Lambda functions that prompted me to write this blog post. The JavaScript code looks something like this:

var lambdaFunc = (someVar) => someVar + 1;
lambdaFunc(2)

To test this out, simply press F12 in your browser, navigate to the console tab and enter the above code.

C++ Lambda Syntax

In C++ they don't use the fat-arrow. They use the array index operators [] as the lambda operator. This allows you to capture the surrounding variables by reference or by value and is my "Yo!! - I'm a Lambda" trigger. The code looks like this:

int main()
{
    auto lambdaFunc = [&] (int someVar) { return someVar + 1; };
    lambdaFunc(2); // now call the function
}

You can try this out using the online C++ compiler here: http://cpp.sh

Rust Lambda Syntax

This one's a bit weird. The syntax looks funny as they use the pipe operator | which is something I am not familiar with.

fn main() {
    let lambda_func = |some_var: i32| return some_var + 1;
    lambda_func(2);
}

You can try this out using the online rust compiler here: https://play.rust-lang.org. Incidentally, the rust compiler forced me to change all my variables to snake_case which I thought was interesting. I like the way you can enforce variable names to keep the code consistent.

Python Lambda Syntax


I like the way Python is all in your face by putting the keyword lambda front and centre. Here's the code:
lambdaFunc = lambda someVar: someVar + 1
lambdaFunc(2)

Again, you can try this out here: https://repl.it/languages/python3

Ruby Lambda Syntax

Ruby is quite similar to JavaScript, with a couple of subtle differences. Instead of the fat-arrow they use a thin-arrow! Also the thin-arrow comes before the function parameter list, whereas other languages put the arrow operator in the middle. Here's the code:

lambdaFunc = -> (someVar) { someVar + 1 }
lambdaFunc.call(2)

Here is the online compiler to check it out for yourself: https://repl.it/languages/ruby

Swift Lambda Syntax


Unfortunately, I have not tested this code but from the documentation, the Swift definition of a lambda is as follows: Lambdas are typically enclosed in curly braces { } and are defined by a function type () -> (), where -> separates the arguments and the return type, followed by the in keyword which separates the closure header from its body.
{ (params) -> returnType in
  statements
}

Notice, here you define the return type for the function where other languages put the function body. Swift also has the in keyword which proceeds the function statements. Our example would look like this:

{ (someVar) -> Int in
  someVar + 1;
}

Go Lambda Syntax

Strangely it looks like Go doesn't support the lambda syntax and the language designers have no intention to add the functionality to the language.

See here: https://groups.google.com/forum/#!topic/golang-nuts/Kfm4t3TShTY

Wrapping up

If you throw a dart in the direction of a modern programming language today, chances are it will support lambdas! More and more languages are borrowing concepts from functional programming. Lambdas are a great way to pass around functions and simplify code.


Contact Me:  ocean.airdrop@gmail.com

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages