elfs: (Default)
[personal profile] elfs

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?


somenumbers
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.

Date: 2013-10-17 11:47 am (UTC)
bolindbergh: (3)
From: [personal profile] bolindbergh
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.

Date: 2013-10-17 06:40 pm (UTC)
blaisepascal: (Default)
From: [personal profile] blaisepascal
Where's the Currying? I just see first-class functions here.

Date: 2013-10-17 07:55 pm (UTC)
From: [identity profile] elfs.livejournal.com
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...

Profile

elfs: (Default)
Elf Sternberg

December 2025

S M T W T F S
 12345 6
78910111213
14151617181920
21222324252627
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 2nd, 2026 06:43 pm
Powered by Dreamwidth Studios