Sunday, January 24, 2016

FizzBuzz and the Roman Numeral Kata are the Same Thing!

"The same, sir."
-- Shakespeare, Coriolanus
Act IV, Scene III, Line 7

As Homer Simpson pointed out, "Coke and Pepsi are the same thing!"

Similarly I plan to show that the FizzBuzz and Roman Numeral katas are the same thing! 

First let's look at the rules of FizzBuzz.

f(x : int) : string
  if 3 | x and 5 | x then "FizzBuzz"
  if 3 | x then "Fizz"
  if 5 | x then "Buzz"
  default string x

*note, 3 | x reads 3 divides x, in other words x / 3 does not have a remainder

 In general we see that we have two (or three) rules and a default value, we are translating from the domain into the codomain following a set of rules, in other words we have a function.

How about the Roman Numeral kata?

f(x : int) : string
    roman-numerals : (int, string)
    lambda((x : int, m : string),
           (k : int, v : string)) : (int, string)
      while k | x then (x / k, concat m v)
    (x, default string) : (int, string)

Again we see a list of rules for translation.

The only real difference to FizzBuzz is the fold across the rules, but we've hinted at this in the FizzBuzz description above.  We stated that FizzBuzz has two (or three) rules, we can rewrite it using a fold with just the two rules using the fold to cover the "and" case.

We see the FizzBuzz and Roman Numeral as having the same shape which we use in the generalization in the "2 version".  Thus using the same function with a set of rules, a defaulting function, and a seed we create both the FizzBuzz and Roman Numeral kata from the same general function!