Learning moment for me. I’ve been learning functional programming for a while, but was faced with an interesting little challenge today. I’ll spare you the problem domain, which is rather boring, and simply give you what’s needed…
A function that takes a positive (that is n>=1) integer, calculate the number of times this number is divisible by 16, and how many times the remainder is divisible by 8, and how many times the remainder of that is divisible by 4, and how many times the remainder of that is divisible by 2. Return each of these values in a key-value structure similar to Ruby’s Hash.
My mind immediately leapt to “oh, this is a perfect fit for some kind of functional technique! Who needs variables?” And then I sat down and tried to write something and my brain very quickly turned to jelly, and I gave in and wrote a very quick imperative version.1 Which looks like this:
Why? My new standard practice with the client in question is to sit down with them at a computer, and if they describe some potentially complex business rule, try and write a simple implementation of the rule in the form of a Ruby (or Python or Scala or whatever) function and verify that it does vaguely what they want. I then chuck it in the bug tracker so when I implement it, I have some nice readable, compilable pseudocode rather than a vague specification. In many cases, implementation is just a matter of writing tests, putting it in the context of the class, documenting and updating the UI and so on. ↩
If you feel like cluttering your example code up with checks to make sure non-positive non-integers raise an exception, feel free. But that’s not really what I’m interested in. ↩