Saturday, May 24, 2014

Bizarre factorial in Clojure

This is my solution for an exercise from the first chapter, Just Enough Clojure in which I had to write a "bizarre version of factorial that uses neither iteration nor recursion":
Tested at the REPL it seems to work fine:
However, there are problems for big enough results because they don't fit into integers:
This can be easily solved using arbitrary precision integers.
You just need to append an N after any number in the calculation, since it's "contagious" to the rest of the calculation:
Now it works:

That's ok but how does bizarre-factorial works?

Let's first examine range function:
So, for example, to get the first 10 positive arbitrary precision integers we'd write:
We might refactor bizarre-factorial using let to create a helper function, positive-ints-until, to make this more explicit:
Let's see now how apply works:
So in the case of bizarre-factorial the apply function is applying the * function to a list of numbers returned by the positive-ints-until helper function.

That's how bizarre-factorial works.

Finally we can use partial to give a better name to the partial application of apply and *:
This version of bizarre-factorial is much more readable.