# Calculating Fibonacci Sequence using Vavr

Fibonacci numbers can be calculated in an idiomatic way using an infinite stream from the Vavr library.

In the following paragraphs, I will demystify this magic spell. 🧙♂️

# The appendSelf() method 📸

In short, it allows appending the result of the mapping function to the end of the stream. The argument of this function is the stream itself. This may sound a bit convoluted, so it’s best to look at a few examples.

When, in the mapping function, we return stream of the several values, they are simply appended to the end of the stream. In this example, the `self`

parameter is ignored.

The most interesting, however, is the use of the `self`

parameter. In this way, we can create an infinite sequence of ones.

Or a sequence of consecutive natural numbers.

Once we understand how it works, we’re close 🤏 to writing a Fibonacci sequence .

# The tail() method 🐁

Each stream consists of a `head`

and a `tail`

. The first element of the stream is called the `head`

, and the other elements are called the `tail`

. Let’s take a look at an example.

It is important to remember that the tail is lazily evaluated. 🥱

# The zip() method 🤐

It combines two iterables into one, pairing their corresponding elements. If one of the two iterables is longer than the other, its remaining elements are ignored. Take a look at the example below.

This and many other methods have been visualized on the RxMarbles website.

# The map() method 🗺️

The name of this method is self-explanatory, but for the sake of completeness, I provide an example below.

# Tuples 🐑🐑🐑

The way of accessing elements inside the tuple is inspired by the Scala language.

Vavr provides tuples containing from 0 to 8 elements. In our case, `Tuple2`

is used because it’s the type returned by the `zip`

method.

# Putting it all together 👫

Imagine we have the beginning of the Fibonacci sequence.

This is how the tail of our stream looks like.

When we `zip`

the `tail`

with the original stream, we will get the stream of pairs (i.e. `Tuples`

).

To compute a new element of the Fibonacci sequence, we just need to sum all the pairs together.

You can see that the last element in the stream is our desired value. But now we’ve lost the first element in the sequence (value `0`

), so we need to prepend our stream with the `head`

element.

Finally, we managed to add a new element to our sequence. But how to do this infinitely? Here `appendSelf`

comes to the rescue!

# Summary 🏁

Vavr offers countless possibilities for creating a concise and expressive code in a functional style. I encourage you to give it a try! 🕺🏻