Thanks to
this post I've started the year discovering a language I never knew existed - and a cool little feature in it.
Imagine you have a function called g
g(5) #returns 10
Now imagine you have another function which undoes whatever happened in g.
undo-g(10) #returns 5
Not too impressive on the face of it. You could guess that g just multiplies by 2 and undo-g divides by 2. The J language comes with some of these built in. Which it calls obverse functions.
4 + 4
8
4 +^:_1 (4)
0
In this function +^:_1 effectively means apply the + function -1 times. You could do it twice:
4 +^:_2 (4)
_4 (In J _4 means -4)
Seem crazy? Stay with it...
How many times do you see this sort of pattern in your code?
OpenFile
ReadData
CloseFile
OpenSocket
SendData
CloseSocket
Look familiar? Well, because J has the idea of obverse functions you get a lovely little syntax that J calls
Under which covers this pattern.
In J it looks like this
f&.g x
Which means apply g to x. Then apply f. Then apply the inverse of g.
obverse(func(verb(x))) #J calls functions verbs
The J documentation lists loads of
cool definitions you can build using under.
Here's the idea in clojure using the under pattern to construct a new definition of multiplication and addition.
It's a cool idea to start the year with. I wonder how many places I'll start seeing this pattern?
For more information about J check out the excellent
J for C Programmers (Rich 2007)