# Computing Fibonacci in RethinkDB

Yesterday I saw @taybin’s RethinkDB driver for Elixir. I didn’t know anything about the language so I started browsing through the documentation, and stumbled on the obligatory Fibonacci example. Of course I immediately got the itch to compute Fibonacci in ReQL. It turned out to be pretty simple.

First, create a table to store the Fibonacci numbers and insert the two base cases:

``````r.tableCreate('fib');
r.table('fib').insert([{id: 0, value: 0},
{id: 1, value: 1}]);
``````

Now the magic:

``````// For each of the elements in the array, insert a new row into the
// `fib` table that sums the values of the previous two rows
r.expr([2, 3, 4, 5, 6, 7, 8, 9, 10, 11]).forEach(function(x) {
return r.table('fib').insert({
id: x,
value: r.add(
r.table('fib').orderBy('id').nth(x.sub(1))('value'),
r.table('fib').orderBy('id').nth(x.sub(2))('value'))
});
});
``````

And voila:

``````r.table('fib').orderBy('id')('value');
// returns [0,1,1,2,3,5,8,13,21,34,55,89]
``````

We might have to prioritize the `r.range` operator (Github issue #875) so instead of typing out

``````r.expr([2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
``````

We could just type `r.range(2, 12)`. A dev team must know its priorities.