Clojure FizzBuzz Without Conditionals

Sure you may have done FizzBuzz before. Maybe you have even done it in Clojure. But have you done it without the use of any conditionals?

As your brain starts to work on the how this we be done, you might be wondering why you should do this in the first place?

There are two very good reasons for this. The first is that it is a kata.

Katas build your code practice

Code katas build your skill through practice. It doesn’t matter if you are a beginner or an expert. Just, like in all those martial arts movies with the swordsman practicing, so must we. We stretch and flex our coding muscles with katas to grow them and keep them in shape.

Yes, you may code every day at work. But it is not the same as kata practice. So much of day to day work involves complexity with large interconnected concerns. Our kata practice cuts the extra complexity out and leaves you alone with a focused small problem.

The second reason involves why you should try it, this time, without conditionals. The answer is creativity.

Constraints build creativity.

It turns out that constraints are a key way to drive creativity. Programming does not only require technical skills, but also creativity. We are seldom asked to build software without constraints. It drives design. Sure, it can be annoying when we have to communicate with a server that is only active on Tuesday and emits its response in Morse Code. But it gives us boundaries to unleash our creative spirit.

So go for it.

Give it a try

Ready? Here are the details.

  • Given a number, if it number is divisible by 3 return “fizz”.
  • If it is divisible by 5 return “buzz”.
  • If it is divisible by 3 and 5 return “fizzbuzz”.
  • Otherwise, just return the number.
  • Don’t use any conditionals like if else case cond.

When you are done, you can check out some of the other solutions. Try not to peek until you have done your version first though.

(There are some really awesome ones so far).

Feel free to link to yours in the comments too :)

Solutions

From @aderth

From @IamDrowsy

From @Bryanwoods

From @defndaines

From me

From @hyPiRion – a couple of notes for this one is that:

1
2
(+)
;; -> 0

and

1
2
(*)
;; -> 1

And once you think about that, you might want to read this :)

Happy Clojure Kataing!

Comments