I'm a recovering programmer who has been designing video games since the 1980s, doing things that seem baroquely hardcore in retrospect, like writing Super Nintendo games entirely in assembly language. These days I use whatever tools are the most fun and give me the biggest advantage.
james.hague @ gmail.com
Where are the comments?
A Programming Idiom You've Never Heard OfHere are some sequences of events:
Take the rake out of the shed, use it to pile up the leaves in the backyard, then put the rake back in the shed.See the pattern? You do something, then do something else, then you undo the first thing. Or more accurately, the last step is the inverse of the first. Once you're aware of this pattern, you'll see it everywhere. Pick up the cup, take a sip of coffee, put the cup down. And it's all over the place in code, too:
Fly to Seattle, see the sights, then fly home.
Put the key in the door, open it, then take the key out of the door.
Wake-up your phone, check the time, then put it back to sleep.
Open a file, read the contents, close the file.While this is easy to explain and give examples of, it's not simple to implement. All we want is an operation that looks like
Allocate a block of memory, use it for something, free it.
Load the contents of a memory address into a register, modify it, store it back in memory.
idiom(Function1, Function2), so we could write the "open a file..." example above as
idiom(Open, Read). The catch is that there needs to be a programmatic way to determine that the inverse of "open" is "close." Is there a programming languages where functions have inverses?
Surprisingly, yes: J. And this idiom I keep talking about is even a built-in function in J, called under. In English, and not J's terse syntax, the open file example is stated as "read under open."
One non-obvious use of "under" in J is to compute the magnitude of a vector. Magnitude is an easy algorithm: square each component, sum them up, then take the square root of the result. Hmmm...the third step is the inverse of the first. Sum under square. Or in actual J code:
+/is "sum." The ampersand, period, colon sequence is "under." And
(Also see the follow-up.)