Discussing software, the web, politics, sexuality and the unending supply of human stupidity.

Code noodling contest: functionalize this

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:

Which is fine and will do the job. But, here’s the challenge to any of my FP-loving readers. Feel free to code-golf the hell out of this. Lisp/Clojure, Scala, Haskell, OCaml, Ruby, Python, JavaScript: whatever your poison, show me how much I suck for using variables. The prize? I might nick your solution and quietly put it into production. And you get over 9000 nerdpoints. And the warm feeling of satiating my curiosity. I don’t care if you don’t output necessarily the same data structures, but you do have to output the right values given the same input.2

  1. 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.

  2. 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.