While watching a fantastic presentation from Fluent Conference 2018 (in San Jose, CA) I came upon the following code snippet written by the presenter Kyle Shevlin:
const double = x => x * 2; const map = fn => xs => xs.map(fn); const doubleEach = map(double); const doubles = doubleEach([1,2,3]);
I saw the first line and I thought:
double is a function that takes a number and returns double the value of that number.
That makes sense to me.
But, as soon as I saw the second line I was confused.
To be able to rip that second line apart, you must understand what
xs is. It's not named very well in the example so that was part of my misunderstanding.
First let's think about what we know about Arrow function basics. We'll use the simpler first line of code (which I understand) as a way of understanding everything else.
const double = x => x * 2;
We know that this simple arrow function takes one parameter (
x) and returns one value (
x * 2).
Ah, a clue to this is that the last thing shown is the value that is returned.
Now,let's turn back to looking at that second line again and discover what is happening there.
const map = fn => xs => xs.map(fn);
The last thing that happens is the
map() function is called on xs.
Here's where we need some inside information, otherwise we are going to continue to be confused. The
xs is an Array.
The Array map() method :
- takes one parameter which is a function it will call on each element of the target Array.
- returns an Array of each element (returned from the function)
Also, keep in mind that calling
xs.map(fn) returns an Array.
const map defines a function which
- takes a function (named
fn) as a parameter
- that function named 'fn' returns an Array
- the Array returned is actually the return from
To me (a long-time dev of imperative programming) that second line is just so clouded.
Let's break it down one more time.
It's that 2nd => that gets me.
It's basically a pass-thru.
Suppose we have the following:
let get5 = fn => xs => 5;
Do you know what that would look like when you call it?
You are telling it to call a function (
get5) which takes a function (we pass in another arrow function
x=>1 which isn't used.
All of that will return a function which we will call immediately with
That last function returns the value
Phew...Do you find this a bit obfuscated?
No wonder Functional programming takes a while to learn.