Exercises in Programming Style–Infinite Mirror

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.

exercises-prog-styles-cover

Fol­low­ing on from the last post, we will look at the Infi­nite Mir­ror style today.

 

Style 7 – Infinite Mirror

This style is real­ly all about recur­sions.

Constraints

  • All, or a sig­nif­i­cant part, of the prob­lem is mod­elled using induc­tion.

 

First, let’s get the list of stop words and put them in a set:

image

and then we will imple­ment the count­ing log­ic using recur­sion:

image

I made some adjust­ments to Crista’s ver­sion here. In her ver­sion, word­Fre­qs is a glob­al state that has been passed in as argu­ment but the recur­sive count func­tion returns noth­ing.

In my imple­men­ta­tion, although I’m still using a muta­ble dic­tio­nary, it’s an imple­men­ta­tion detail that is not exposed to the out­side world. I could have used a Map here instead, but con­stant­ly updat­ing a Map is real­ly clum­sy, plus Map per­forms real­ly poor­ly in this type of use pat­tern.

 

Then we have anoth­er recur­sive func­tions, for print­ing out the word fre­quen­cies:

image

and then some code to tie every­thing togeth­er:

image

 

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