I’ve been learning f# recently, it is a very powerful and elegant language and hopefully we will be using it for real development in the future. One of the first things I tried was writing a version of the classic Fizz-Buzz interview question (for integers from 1 to 100 print Fizz-Buzz if divisible by 15, Fizz if divisible by 3 and Buzz if divisible by 5).
In an effort to massively overcomplicate a trivial question I ended up defining a set of rules that could be applied to arbitrary inputs. The definition of a rule was:
I then set about implementing the mod 3 and mod 5 rules and hit a problem. Ideally we should be able to apply our rules to any integer type, but because of the well known problem of .Net lacking an INumeric/IIntegral interface or equivalent this wasn’t possible and I ended up with separate rules for each integer type:
Not very satisfactory! I really wanted a generic ModThree function that can be applied to any number that supports the mod operator. In fact we can get this behaviour using some Peano style arithmetic:
(Note we must make the function inline so it is not given a concrete type signature on first use)
The key here is are the generic zero and one functions defined in the first two lines. These give a one and a zero of type of the value they are called with. With these defined we can then increment a variable of type ‘b until it is equal to the value passed in of type ‘a. Then we can mod our value of type ‘b. Of course this is hopelessly inefficient if we are modding by a large number.
So there we have it, a small part of a hideously overcomplicated and inefficient FizzBuzz solution, interesting though.