Exercises in Programming Style–Style 1

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



I was at Joy of Cod­ing ear­lier this year and one of the high­light for me was Crista Lopes’ keynote  Exer­cises in Pro­gram­ming Style.

Crista demon­strated how a sim­ple prob­lem of cal­cu­lat­ing term fre­quency can be writ­ten in a plethora of ways, including:

The point of these exer­cises is to allow you to see that there are many solu­tions to the same prob­lem, and that each comes with a set of con­straints that needs to be com­mu­ni­cated.


I really enjoyed the talk and bought Crista’s book so I can go through all 33 approaches in my own time!


It’s taken me a lit­tle while to find the time to do this, but I was finally able to make a start last week­end. Over the next cou­ple of weeks I hope to share with you my ports of Crista’s Python solu­tions in F# and my takeaways.

If you like what you see then please buy the book and sup­port Crista’s work!


Style 1 – Good Old Times

This style was com­mon­place in early 50s when hard­ware lim­i­ta­tions had some hard constraints.


  • Very small amount of pri­mary mem­ory, typ­i­cally orders of mag­ni­tude smaller than the data that needs to be processed/generated.
  • No iden­ti­fiers – i.e. no vari­able names or tagged mem­ory addresses. All we have is mem­ory that is address­able with numbers.


Get the source code here.

As you can expect, not being able to use iden­ti­fiers really stops you in your tracks and made an oth­er­wise sim­ple task so much more com­plex (also makes you appre­ci­ate the work of lan­guage and hard­ware design­ers that came before us).

The imple­men­ta­tion feels deeply unnat­ural due to the con­straints we have imposed on our­selves, and that’s kinda the point of these exercises.

The absence of iden­ti­fiers for instance, forces us to lump a bunch of global vari­ables into an array that acts as our ‘pri­mary mem­ory’ for the pro­gram and forces you to remem­ber which index cor­re­sponds to what.

This style is really at odds with how one would code in F# (prob­a­bly even more so than Python!), as by design F# nudges you towards code in a func­tional style — using immutable val­ues, recur­sion, using types to drive your pro­gram, etc.

Warning, Conferences ahead!

Update 24/08/2015 : some help­ful peo­ple pointed out that I’ve missed a cou­ple of other notable con­fer­ences here, including:


It’s almost that time of the year again, that last stretch of the year when we have so many good con­fer­ences in UK and Europe.




First we have quite a treat in Kats Conf, on the 12th Sep in Dublin. An unbe­liev­able list of speak­ers include Joe Arm­strong, Francesco Cesarinni, Edwin Brady, Amanda Laucher and Phil Trelford!

Ses­sions span across a num­ber of FP lan­guages – Erlang, Scala, F#, Idris to name a few.

What’s more, it’s great value for money. Ticket is only 25 euro, and if you fancy going to Erlang Fac­tory Lite the day before you can even get a combo ticket for 50 euro.



Shortly after Kats Conf, there’s Dev­Day in Krakow on 17th and 18th Sep, with some well known speak­ers in the .Net space includ­ing our very own F# machine learn­ing expert Math­ias Bran­dewinder!



Then on the 26th Sep, there’s DDD East Anglia over in Cam­bridge, a one-day free event that’s organ­ised by devel­op­ers for developers.

The pro­gramme is not out yet but looks like I’ll be giv­ing my “F# in the Real World” talk there.



Round­ing off a rather busy Sep­tem­ber, there’s code.talks in Ham­burg on the 29th and 30th Sep. I’ll be giv­ing my “Tour of Pro­gram­ming Lan­guages” talk there and I’m really look­ing for­ward to vis­it­ing Ham­burg for the first time.




Hot on the heels of OSCON in Port­land, it’s com­ing to Europe for the first time, in Ams­ter­dam on 26th and 27th of Oct.

Some pretty cool tech com­pa­nies will be there – GitHub, DataS­tax, Google, Thought­Works, Pay­Pal, Heroku and Spo­tify to name a few! I will be talk­ing about “Mod­el­ling Game Econ­omy with Neo4j” there.

Rachel Reese from Jet.com is also com­ing over from the US to talk about build­ing reac­tive ser­vices with F#!



CodeMesh has been my favourite con­fer­ence the last cou­ple of years and it’s the place to be to learn about emerg­ing tech­nolo­gies and lan­guages from some of the best peo­ple in the industry.

This year, you can learn from the likes of:

  • Sir Tony Hoare (Tur­ing Award Winner)
  • John Hughes (QuickCheck)
  • Robert Vird­ing (co-creator of Erlang)
  • Don Syme (cre­ator of F#)
  • Joe Arm­strong (co-creator of Erlang)
  • Evan Czaplicki (cre­ator of Elm)
  • Ste­fan Karpin­ski (co-creator of Julia)
  • William Byrd (co-creator of miniKanren)
  • Bruce Tate (author of the 7 lan­guages in 7 weeks books)
  • and F# super­stars Phil Trelford and Tomas Petricek!

Seri­ously, if you’re look­ing for a con­fer­ence that’ll chal­lenge you intel­lec­tu­ally (and hon­estly, hurt your brain a lit­tle!) then CodeMesh is the place to be on Novem­ber 3rd and 4th in London!



Over in Malmo, there’s also Ore­dev from Novem­ber 4th to 6th, which is a very well attended con­fer­ence with thou­sands of atten­dees each year.

I have heard plenty of good things about Malmo and Ore­dev, and it was per­son­ally rec­om­mended by Phil Trelford so you just know it’s gonna be good!

And this year there’ll be a good F# pres­ence, with Rachel Reese, Paul­michael Bla­succi, Evelina Gabasova and myself all talk­ing about F# 

Oh, and Adam Torn­hill (who you might know as the author of Code as Crime Scene) will be there too.



Finally, Build­Stuff is hap­pen­ing again from Novem­ber 18th to 20th. It’s still early days and only a cou­ple of speak­ers have been con­firmed but already you can count the likes of Uncle Bob, Michael Feath­ers, Trisha Gee, Randy Shoup, Pieter Hin­t­jens and Kevlin Hen­ney amongst them.

Based on my expe­ri­ence from last year, I’m sure Build­Stuff is going to be great again this year.


With so many great con­fer­ences com­ing up, I’m really excited to be able to learn from some of the best peo­ple in the indus­try and hope to catch you at some of these events!

More fun with APL

Note: see the rest of the series so far.


I stum­bled across this post the other day and prob­lem 2 seems like some­thing I can eas­ily do in APL since it essen­tially requires you to inter­leave two arrays.

The prob­lem is:

Write a func­tion that com­bines two lists by alter­nat­ingly tak­ing ele­ments. For exam­ple: given the two lists [a, b, c] and [1, 2, 3], the func­tion should return [a, 1, b, 2, c, 3].

Here’s the solu­tion I have come up with:


since it uses both \omega (right argu­ment) and \alpha (left argu­ment) so it’s a dyadic func­tion, let’s test it out:

'a' \ 'b' \ 'c' \ p2 \ 1 \ 2 \ 3

=> a 1 b 2 c 3

Here’s how it works:

  • con­cate­nate the two argu­ments together, with the left argu­ment first (\alpha, \omega)
  • reshape \rho the con­cate­nated vec­tor into 2 rows, so that you have effec­tively placed \alpha and \omega into a matrix, i.e.

a \ b \ c\\*    1 \ 2 \ 3

  • trans­pose that matrix

a \ 1\\*    b \ 2\\*    c \ 3

  • reshape \rho the trans­posed matrix into a vec­tor, and that’s it!


My picks from OSCON keynotes

So OSCON came and went, and whilst I haven’t seen the record­ing for any of the ses­sions, the keynotes (and a bunch of inter­views) are avail­able on YouTube.

Unlike most con­fer­ences, the OSCON keynotes are really short (aver­age 10–15 mins each) and hav­ing watched all the pub­lished keynote ses­sions here are my top picks.


Simon Ward­ley — Sit­u­a­tion Nor­mal, Every­thing Must Change

I’m a big fan of Simon’s work on value chain map­ping, and his OSCON 2014 keynote was one of the most mem­o­rable talks for me last year.


Simon started by point­ing out the lack of sit­u­a­tional aware­ness on the part of enter­prise IT. Enter­prise IT lives in a low sit­u­a­tional aware­ness envi­ron­ment that relies on back­ward causal­ity and ver­bal rea­son­ing (or story telling), and has no posi­tion or movement.

Whereas high-level sit­u­a­tional aware­ness envi­ron­ments (e.g. mil­i­tary com­bat) are con­text spe­cific, you have posi­tions and move­ments and usu­ally employ some form of visual reasoning.


Mil­i­tary actions are dri­ven by your sit­u­a­tional aware­ness of the where and why, but in Busi­ness we have a tyranny of actions.


and this is where Simon’s value chain map­ping comes in. With maps, you can add posi­tions to your com­po­nents based on the val­ues they pro­vide, as well as move­ment as they evolve from the unchar­tered world (chaotic, uncer­tain, unpre­dictable, etc.) to become industrialized.


In terms of method­ol­ogy, there’s no one size that fits all.

Agil, XP and Scrum are very good on the left side (the unchar­tered world), par­tic­u­larly when you want to reduce the cost of change.

On the right side, as things become indus­tri­al­ized, you want to reduce the cost of devi­a­tion and Six Sigma is good.

In the mid­dle where you want to build a prod­uct, lean is par­tic­u­larly strong.


If you take a large scale project, rather than hav­ing a one-size-fits-all method­ol­ogy, you can employ dif­fer­ent method­olo­gies based on where that com­po­nent is in its evo­lu­tion. For devel­op­ers, this is no dif­fer­ent to the argu­ments for poly­glot pro­gram­ming, or poly­glot per­sis­tence, because no sin­gle lan­guage or data­base is good for all the prob­lems we have to solve.

Why should the way we work be any different?


By over­lap­ping the value chain maps for dif­fer­ent areas of the busi­ness you can start to iden­tify over­laps within the orga­ni­za­tion, and a snip­pet from his most recent post shed some hor­ri­fy­ing light on the amount of dupli­ca­tion that exists:

…To date, the worst exam­ple I know of dupli­ca­tion is one large global com­pany that has 380 cus­tomised ver­sions of the same ERP sys­tem doing exactly the same process…

The US air force dis­cov­ered that, as peo­ple came up with new ideas they tend to add fea­tures to that idea and made it bet­ter (and more com­plex); they then added even more fea­tures and made the idea so com­plex it’s com­pletely use­less to any­one, and that’s approx­i­mately where they shipped it. (for reg­u­lar read­ers of this blog, you would prob­a­bly have read about this obses­sion of fea­tures many times before)

So Lt. Col. Dan Ward came up with FIST (Fast, Inex­pen­sive, Sim­ple and Tiny), which in his own words:

FIST stands for Fast, Inex­pen­sive, Sim­ple and Tiny. It’s a term I use to describe a par­tic­u­lar approach to acqui­si­tions and sys­tem devel­op­ment. As you might guess, it involves using a small team of tal­ented peo­ple, a tight bud­get, a short sched­ule and adher­ing to a par­tic­u­lar set of prin­ci­ples and practices…

in other words, small is beau­ti­ful, and it’s a theme that we have seen repeat­edly — be it microser­vices, or Amazon’s two-pizza teams, etc.

And as you impose con­straints on the teams — tight bud­get, short sched­ule — you encour­age cre­ativ­ity and inno­va­tion from the teams (some­thing that Kevlin Hen­ney also talked about at length dur­ing his Joy of Cod­ing clos­ing keynote).


How­ever, even with small teams, you still have this prob­lem that things need to evolve. For­tu­nately we have a solu­tion to that too, in what is known as the three party sys­tem where you have:

  • pio­neers — who are good at explor­ing the unchar­tered world
  • set­tlers — who are good at tak­ing half-baked ideas and make use­ful prod­ucts for others
  • town plan­ners — who are good at tak­ing a prod­uct and indus­tri­al­is­ing it into com­mod­ity and utility


Once you have a map, you can also start to play games and antic­i­pate change. Or bet­ter yet, you can manip­u­late the map.

You can accel­er­ate the pace of evo­lu­tion by using open prac­tices — open source, open API, etc. Or you can slow the process down by using patents, or FUD.

The key thing is that, once you have a map, you can see where things are mov­ing and visu­ally rea­son about why you should attack one com­po­nent over another. And that’s how you can turn busi­ness into sit­u­a­tional aware­ness first, and actions after.

As things move from prod­uct to com­mod­ity, they enable a new gen­er­a­tion of ser­vices to spawn up (won­der), but they also cause death to orga­ni­za­tions stuck behind the iner­tia bar­rier (death).swardley_21

This is a pat­tern that Simon calls War, Peace and Won­der, and is iden­ti­fi­able through weak sig­nal detec­tion and see roughly when these changes will likely happen.


Simon fin­ished this bril­liant ses­sion with three lessons:

  1. if you’re a start up, have no fear for large cor­po­rates because they suck at sit­u­a­tional awareness;
  2. the future is awe­some, and pio­neers have already moved into the space of open hard­ware and open biology;
  3. open source itself is chang­ing, we have new peo­ple com­ing in as new settlers


I hope you enjoyed Simon’s talk, his blog has much more infor­ma­tion and goes into each of these top­ics in a greater deal of detail. If you fol­low him on Twit­ter (@swardley) he also post reg­u­lar tit­bits of wis­dom, which I have started to col­lect.


James Pearce — How Face­book Open Sources at Scale

…We use in pro­duc­tion what we open source, and we open source only what we use in production…

- James Pearce

Nuff said 


Mar­tin Fowler — Mak­ing Archi­tec­ture Matter

I don’t like the term “soft­ware archi­tec­ture” as it sum­mons up these images of some senior per­son in an orga­ni­za­tion who’s set­ting rules and stan­dards on how soft­ware should be writ­ten but hav­ing actu­ally writ­ten any soft­ware for maybe 10 or 20 years. These archi­tects, Joel Spol­sky use the term “archi­tec­ture astro­nauts”, often cause a lot of prob­lems in soft­ware projects. So the whole term “archi­tect” and “archi­tec­ture” has a kinda nasty taste to it.

- Mar­tin Fowler

For me, the key points from this talk are:

  • the notion that archi­tects shouldn’t code is wrong (or, don’t be an ivory tower architect!)
  • archi­tec­ture is really the shared under­stand­ing of the system’s design amongst its expert developers
    • archi­tec­ture dia­grams are just (often imper­fect) rep­re­sen­ta­tions of this shared understanding
    • as soft­ware projects grow, what mat­ters the most is for you to ensure a good shared under­stand­ing between peo­ple lead­ing the project
  • archi­tec­ture is also the deci­sions that you wish you could get right early
    • your con­cern is there­fore the deci­sions that are hard to change, e.g. the pro­gram­ming language
  • com­bin­ing the two def­i­n­i­tions above, and you can think of archi­tec­ture as the “impor­tant things that I need to always keep in my head whilst I’m work­ing on the system”
  • when con­fronted with requests for more fea­tures over qual­ity, don’t make the moral argu­ment of craftsmanship
    • when it comes to a bat­tle between crafts­man­ship and eco­nom­ics, eco­nom­ics always wins
  • a com­mon fal­lacy is to think that soft­ware qual­ity is some­thing that can be traded off for cost (like you do with cars or cellphones)
  • soft­ware has both exter­nal (vis­i­ble to users) as well as inter­nal (good mod­u­lar­ity, etc.) and archi­tec­ture is about inter­nal quality
    • what mat­ters with inter­nal qual­ity is the long term picture
    • well main­tained code base gives you a plat­form to build upon and can make future devel­op­ment eas­ier and faster
    • poorly main­tained code base makes it harder and harder for you to make changes to
    • this is why archi­tec­ture matters!


Raffi Kriko­rian — Hack­ing Conway’s Law

Conway’s law has been a trendy topic at con­fer­ences this past 12 months, and every­one is basi­cally singing the same tune — apply Conway’s law in reverse and orga­nize your com­mu­ni­ca­tion struc­ture to fit the soft­ware you want to build.


OSCON is com­ing to Europe!

At long last, we’ll see a ver­sion of OSCON in Europe this year, on 26th-28th Octo­ber in Ams­ter­dam. Some pretty cool tech com­pa­nies will be rep­re­sented there — GitHub, DataS­tax, Google, Thought­Works, Pay­Pal, Heroku and Spo­tify to name a few, and of course, our very own Gamesys 

I will giv­ing a talk on the work I did with Neo4j a while back, which you can read all about in this post.

p.s. Rachel Reese (of Jet) is com­ing over from the US and talk­ing about build­ing reac­tive ser­vice with F#!



Tokyo Experience Report

Quite a few peo­ple have asked me about my trip to Tokyo recently and to see some pic­tures, so here’s a com­pletely non-technical post about my expe­ri­ence there! Hope­fully this will help your plan­ning if you’re look­ing to visit Japan in the near future.



There are two inter­na­tional air­ports for Tokyo – Narita and Haneda. Narita is about 1hr 30mins from Tokyo city cen­tre by train whilst Haneda is about 30 mins away.

We stayed in Shim­bashi, which is one direct train jour­ney away from both air­ports. It’s also very close to a num­ber of notable attrac­tions such as the Impe­r­ial Palace, Tokyo Tower and Tsuk­iji Fish Market.

There are also coaches that can take you directly to a num­ber of hotels in Tokyo includ­ing Park Hotel Tokyo where we stayed.


We had a good view of the Tokyo Tower from our room and it’s quite a sight at night.



There aren’t many pub­lic Wifi spots (though you can find them in Star­bucks and other cafes), but you can rent a mobile wifi egg at both Narita and Haneda air­port for about £7-£8 a day. You get really good speed with these and they work on the under­ground as well.


Tokyo F# user group

On the day I arrived I actu­ally met up with the Tokyo F# user group and gave a talk on F# at Gamesys. Big thanks to Yuk­i­tos for set­ting it up and the guys for attending!

If any of you F# folks find a chance to visit Japan you should def­i­nitely hook up with these guys too, they showed off some inter­est­ing stuff they’ve been work­ing on.

I was too jet-lagged and brain-dead that it didn’t even occur to me to get a snap with the group  I had just trav­elled back to Lon­don from Poly­conf; jour­neyed across Lon­don from Luton to Heathrow; then took a 16hr flight to Tokyo with a 2hr stop in Ger­many; I was barely func­tion­ing by the time I got to the meetup.

In hind­sight I should have met the guys maybe a day later so I’m in bet­ter shape and am able to join them for a beer or two afterwards.



The food in Tokyo was not as expen­sive as we imag­ined, you can get a bowl of ramen for around 800 yen (about £4) although sushi tends to be rel­a­tively expensive.

While you’re here you should def­i­nitely try the ramen, be warned though, they are very rich in flavour and a wee bit salty for my taste, espe­cially the miso flavoured ones.

Pretty much every restau­rant we tried was good, many of them are tiny though, so there might only be stand­ing room.

Don’t for­get to ask for a non-smoking seat!

Not all restau­rants have a non-smoking areas but it doesn’t hurt to ask. It’s not a pleas­ant expe­ri­ence to be sand­wiched between two groups of chain-smoking Japan­ese men whilst you’re try­ing to enjoy your meal…

If you go in the sum­mer, it’s also worth try­ing out the Buck­wheat noo­dle which is usu­ally served cold with a bowl of soup or soy sauce to eat it with. In 30 degrees heat, this is sur­pris­ingly refreshing!


And then there’s the bento/set meals that you tend to get at lunch time. Again, these are really afford­able and gen­er­ally good qual­ity and just enough for one person.


We didn’t see any small food stands on the street (like in Seoul and Tai­wan) but then again, you’re never more than a few mins walk from a restau­rant, so find­ing a place to eat is never an issue in Tokyo.


Tsuk­iji Fish Market

If you go to Tsuk­iji fish mar­ket really early (say, 6am) then you can see the salmon auc­tions. It wasn’t our thing so we just explored the nearby restau­rants for some fresh seafood for lunch and boy they didn’t disappoint! 


Many of the restau­rants have sim­i­lar dishes – mainly rice with sashimi/fish roe/etc., but prices can dif­fer by up to 20~25%.

Some places claim to have no-tax, but what they really mean is that the prices on the menu do not include tax, but they still charge you ~7% tax on the final bill.

In the outer mar­ket, there are also lots of small food stands where you can buy grilled seafood/fresh oyster/etc., there was even a shop that sells king crab legs (though it’s one of the more expen­sive things you’ll find there).

Oh, and this place gets really really busy on week­ends so avoid going there on Sat­ur­days and Sun­days if you can!


Ghi­bli Museum

We really wanted to visit the Ghi­bli museum just out­side of Tokyo, hav­ing grown up with so many of its clas­sic anime – My Neigh­bor Totoro, Porco Rosso, Nau­si­caa of the Val­ley of the Wind, Princess Mononoke and Spir­ited Away to name a few.

Much to our sur­prise, it was com­pletely booked out for the month of July… Word of advice, book online before you travel if you wanna stand a chance of get­ting in.

It’s a minor con­so­la­tion that there’s a big wall clock near our hotel that’s mod­elled after Howl’s Mov­ing Cas­tle and it “comes alive” at sev­eral spe­cific times a day.


Tokyo Tower

This is Japan’s answer to the Eif­fel Tower, and I’m sorry to say that it’s a fairly weak answer at that – the view is just not com­pa­ra­ble to the Eif­fel Tower unfortunately. image


Mei­jin Shrine

A short walk from Yoyogi sta­tion is the Mei­jin Shrine, which is sit­u­ated right next to the National Park. The whole area is cov­ered with these great big trees and extremely well preserved.



Once inside, you can buy charms as well as a wooden board to write down your wishes.


The sou­venir shop also sells quite a few vari­ety of locally pro­duced tea in dif­fer­ent forms – tea leaves, tea bags as well as pow­der. I’ve never tried mak­ing tea from pow­der before but it’s really con­ve­nient and you can also make cold/ice tea from them too. Now that I’ve had a taste, I wish I had bought a few more bags of them at the time.

If you find green tea’s flavour a lit­tle too strong, you might wanna try the roasted brown rice tea which has a milder flavour but still has that nice aroma that green tea has – yeah, I love my tea! 


Sanjo Shrine

Com­pared to the Mei­jin Shrine, the Sanjo Shrine feels much more touristy – a long stretch of road lead­ing to the shrine is lined with end­less sou­venir shops and food stands.

I didn’t enjoy it very much (but I still couldn’t help myself and bought some snacks and sou­venirs along the way, oh the shame…), as it was crowded and feels very commercialized.





Cat cafes are a big thing all over Asia, and we had to visit them whilst we’re here. We went to two cat cafes near Ike­bukuro sta­tion, and Neko­robi is the old­est and most famous one in Tokyo (or so the hotel staff tells us).

Neko­robi costs 1000 yen (roughly £5) for the first hour (drinks are included) and is basi­cally the size of an apartment.

We got there early (around lunch time when it opens) and man­aged to enjoy some qual­ity time with the cats before other peo­ple started to show up.




The cats, as they do, spend most of their time sleep­ing and ignor­ing us.  They’re very approach­able though and didn’t mind us pet­ting them at all. How­ever, they didn’t fancy play­ing, except for this lit­tle cutie whom took a real lik­ing to us!


Nekono iru kyukeisho Nikukyu (299)

This place is big, and with lots of cats sleep­ing and won­der­ing around. There are lots of manga and books on the shelves (all in Japan­ese unfor­tu­nately) and most peo­ple there are just chill­ing out, drink­ing free cof­fee and reading.






It’s slightly more expen­sive com­pared to Neko­robi – 200 yen (£1) per 10 mins + extra if you want drinks as well. If you pay another 500 yen (around £3) you can also have the hon­our of feed­ing the cats treats and watch them swamp all around you!


Over­all Impression

We really enjoyed our time there, Tokyo is a lovely city, every­thing is very clean and tidy. The trains are always on time, clean and well air-conditioned (I hadn’t realise how dirty the Lon­don under­ground trains are until I got back and noticed the stark contrast).

Lan­guage can be a bar­rier, many peo­ple in the shops didn’t speak Eng­lish but we man­aged to get by with Chi­nese (it was the same when we were in Seoul as well, a side-effect of the grow­ing middle-class in China I suppose)


And as if to wel­come me back to my famil­iar sur­round­ings, on the jour­ney back home we saw this in the tube sta­tion. Yup, I’m def­i­nitely home!