Lambda & Map in Google Sheets — Functional Programming Style taking over the world?
On Functional Programming
I have always been a fan of the functional style of programming. My first contact with It happened during my undergraduate degree in Physics, when I first had contact with Mathematica (today Wolfram Language). I found it magical when I saw that with a few lines of code, and without the need to open and close loops, I could write my code in a much more compact and elegant way.
Time went by, and little by little I saw Java and Python making modest steps in that direction, but nothing that matched what is possible to do in Mathematica.
For those who are not yet familiar, Lambda notation in Mathematica can be expressed in a few different ways. From the most verbose:
f = Function[x, x²]
to the more compact:
f = (#²)&
If I want to map the function f into a range, you can use:
Map[f, {1,2,3,4}]
or the more compact form
f /@{1,2,3,4}
You don’t even have to declare f in advance to map into a list, which more compactly can be written as:
(#²)& /@ {1,2,3,4}
At first glance the notation may seem a bit scary, but once you get used to it, it proves to be extremely elegant and compact. You can create an account and play for free with Wolfram Language here.
But, what is the relationship with Google Sheets?
Along with other exciting news, today Google announced that it will support lambda functions and another set of functional operators in its spreadsheet solution.
The way it operates is very similar to what we have in Mathematica. For the Lambda function it works in the exact same way, you just has to change Function -> Lambda:
f = Lambda(x, x²)
For the Map function, the only difference is the order of the arguments:
Having the possibility to work with functional operators in sheets is a great evolution, and opens a whole new range of possibilities, being much more intuitive than the use of ArrayFormulas.
IMHO the functional model is much more intuitive for data manipulation. I believe that with this new feature, Sheets can help popularize this elegant and under-explored way of programming.
What about you? Did you like the new features?
PS: Excel has Lambda function and all the new Google Sheets operators since 2021