Everyone seems to be writing code to generate a fibonacci sequence these days. So I thought I’d add my own contribution.

We’re going to generate the fibonacci sequence by simulating a fast-breeding rabbit population. This is not the most efficient way to generate fibonacci numbers.

First we need to define the rabbit lifecycle. At each stage of the simulation, young rabbits will age to become fully grown rabbits. Rabbits will live on themselves (for simplicity, immortal rabbits are assumed) and produce a new young rabbit offspring. We can describe this lifecycle in a map:

(def rabbit-lifecycle {:young-rabbit [:rabbit]
:rabbit [:rabbit :young-rabbit]})

Now we can simulate a rabbit population by iteratively generating the next population from the previous population. We can do this with the handy iterate function in Clojure, given a starting population which is a list containing just one young rabbit:

(def rabbit-population
(iterate (partial mapcat rabbit-lifecycle)
'(:young-rabbit)))

Let’s test that this is working:

(doseq [pop (take 5 rabbit-population)]
(println pop))
(:young-rabbit)
(:rabbit)
(:rabbit :young-rabbit)
(:rabbit :young-rabbit :rabbit)
(:rabbit :young-rabbit :rabbit :rabbit :young-rabbit)

Looking good. Finally we can get our fibonacci sequence by counting the rabbits at each step:

(def fibs (map count rabbit-population))
(take 15 fibs)
=> (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610)

Victory is ours!

### Like this:

Like Loading...

*Related*