Exercises in Programming Style–Code Golf

NOTE : read the rest of the series, or check out the source code.

If you enjoy read­ing these exer­cises then please buy Crista’s book to sup­port her work.


Fol­low­ing on from the last post, we will look at the Code Golf style today.


Style 6 – Code Golf

This style came from Code Golf, which is also often asso­ci­at­ed APL, anoth­er lan­guage that I’ve had a lot of fun with in recent months!



  • As few lines of code as pos­si­ble


Well, cov­er your eyes folks, this one ain’t pret­ty…

The lines are so long that you have to click on the image to view it in full just to be able to read the orig­i­nal source code prop­er­ly…


But, but, but, it does solve the term fre­quen­cy prob­lem in only 3 lines of code! 3 lines!

3 unbe­liev­ably hard to read lines of code 

And that’s where this style falls down, the pur­suit for brevi­ty often comes at the expense of read­abil­i­ty.

It can also be argued that what we have done here is rear­rang­ing the steps in few­er lines with­out nec­es­sar­i­ly reduc­ing the num­ber of steps. That is, we haven’t reduced the num­ber of things that needs to be kept in our head in order to under­stand what this piece of code is doing to solve the prob­lem.

On this note, APL’s syn­tax is often described as unread­able, but I think the prob­lem is not read­abil­i­ty but rather famil­iar­i­ty. Its syn­tax and built-in abstrac­tions are both alien to most devel­op­ers, and very dif­fer­ent to what they’re used to.

When I was learn­ing API, there were a few men­tal hur­dles that I need­ed to jump through:

  • glyph-based func­tion names
  • func­tions have monadic (i.e. pre­fix) and dyadic (i.e. infix) forms
  • every­thing works on matri­ces as well as scalars
  • prece­dence always flow from right-to-left, except when braces are used

once I built up some famil­iar­i­ty with the lan­guage I actu­al­ly found APL pret­ty easy to read.


You can find all the source code for this exer­cise here.