Today we are going to look at generating the nth fibonacci number using case in Clojure. This seems to be familiar with Java’s switch case.

I wrote a function to calculate fibonacci numbers.

(defn fibonacci [x]
(case x
1 0
2 1
(+ (fibonacci (- x 1)) (fibonacci (- x 2)))))

Case takes x as an expression. Then we have constant-cases and result expressions. Here we have 1 and 2 as the constant-cases and 0 and 1 are the result expressions. In the end there is the option of supplying a default case which I am using for the fibonacci definition.

When using the above I quickly faced problems when trying to run it with bigger numbers. It becomes slow fastly. To take care of that we use memoize and +’ operator.

(def fibonacci
(memoize
(fn [x]
(case x
1 0
2 1
(+' (fibonacci (-' x 1)) (fibonacci (-' x 2)))))))

Here we changed fibonacci to be equal to a memoized function. Memoize keeps a cache of older results. This helps in the function not being called repeatedly. Also the addition operator was updated so that we can get bigint when needed.

It solves the problem of big numbers in case we call it with smaller numbers first. e.g call it with 100 then 200 then 300 and so on and it will give correct results. Obviously that’s a problem. Try and figure out how to solve it while I do the same 😀

### Like this:

Like Loading...

*Related*

Pingback: Writing about Clojure | ansh bansal