Showing posts with label j language. Show all posts
Showing posts with label j language. Show all posts

Sunday, December 30, 2012

go(ing) under

Lots of people like go and this year I began to find it unavoidable - I'm even ending the year with go being the main language that helps pay my bills!

One of the things that go lets you do is pass functions around.
I started the year talking about under from the j language. Which lets you 'bookend' some function with another function (a verb) and a function which undoes that function (obverse).
A great example is Pythagoras' theorem:
  1. You perform some 'pre-processing' on each value (squaring)
  2. You add all the values up
  3. You square root the result
I started the year talking about under in clojure. Here it is implemented in go. Complete with functions being passed around, closures, and functions returning functions. Happy new year!

Wednesday, January 4, 2012

Under: A new Idiom from the J language

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)