Calculating Fibonacci Sequence using Vavr

Fibonacci infinite sequence
Leonardo Bonnaci, later nicknamed “Fibonacci” (source)

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.

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.

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.

Visualization of the zip method from RxMarbles

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.

Putting it all together 👫

Imagine we have the beginning of the Fibonacci sequence.

Test verifying Fibonacci sequence

Summary 🏁

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store