Calculation of nth Fibonacci number is one of the common example of introduction to programming. Here I wanted combine this example with some Clojure utilities in four ways.

Recursive with stack usage and memoize

Recursive with tail call

With reduce function

Imperative way with refs

fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2)

1. Recursive with stack usage and memoize

This example isn’t the ideal way but it’s important to understand how recursion works. Clojure has no tail recursion optimization by default. This example causes stack overflow error.
memoize is a useful function to speed up when we’re sure the result of the function is always same and there is no need to call once more for side effects.

Oh we received an number overflow error. What is the problem? Clojure use java.lang.Long as the default precision type and we reached the maximum possible value. There are two options in this condition:

Using clojure.lang.BigInt with (bigint x) or adding N to end of the number 123N. This will be expensive if we usually stay in Long range.

Using +' operator. It automatically uses clojure.lang.BigInt if necessary when the overflow occurs.

Aritmetic operations have more best practices, it’ll be too much to try handling all of them here.