Log in

No account? Create an account
entries friends calendar profile Elf Sternberg's Pendorwright Projects Previous Previous Next Next
Now I get mapping and currying... - Elf M. Sternberg
Now I get mapping and currying...

Okay, so I’m slow to the party.  Forgive me.  I was reading Reginald Braithewaite’s Javascript Allonge and I understood where he was heading long before he got there, and the lightbulbs were going off in my head, and although his technique for getting there was far more verbose than my own, I finally grokked the big point. It’s a classic programmer’s rule of productivity: If you find yourself doing something more than twice, automate it!

We do this all the time with makefiles and functions, but Braithwaite’s book brought the question down to the micro level: If you have to apply the same transformation to three different arrays, or if you have to apply three transformations to the same array, why are you doing it like this:

somenumbers = [....]
squared = somenumbers.map (x) -> x * x
cubed = _somenumbers.map (x) -> x * x * X
halved = somenumbers.map (x) -> x / 2

When you could do this?

toMap = (a) -> (f) -> a.map(f)
[squared, cubed, halved] = [
    ((x) -> x * x), 
    ((x) -> x * x * x), 
    ((x) -> x / 2)].map(toMap(somenumbers))

By creating a function that already has the array to process, and then processing it multiple times, you prevent the emergence of typos in your code caused by repeatedly typing the variable name. And you accurately put the point of your code in the left-hand column once, which is very attractive to me.

This is good stuff, man. And Coffeescript is so much more expressive than Javascript in the same realm. Imagine writing toMap in JS:

function toMap(a) {
    return function toMap(f) {
        return a.map(f);

A lot of clutter to express what Coffeescript expresses so cleanly.

3 comments or Leave a comment
bolindbergh From: bolindbergh Date: October 17th, 2013 11:47 am (UTC) (Link)
This works well for up to three items. Beyond that, it becomes increasingly error prone to have the result variables and their corresponding transformation functions in two separate lists that need to be kept in sync.
blaisepascal From: blaisepascal Date: October 17th, 2013 06:40 pm (UTC) (Link)
Where's the Currying? I just see first-class functions here.
elfs From: elfs Date: October 17th, 2013 07:55 pm (UTC) (Link)
There are methods in the Allonge library that would automatically "flip" (reverse the order of arguments) and curry map() for you. Braithewaite hasn't gotten there yet, but I'm already understanding the points he's about to make...
3 comments or Leave a comment