Generating Fibonacci Sequence with Immutability

Generating Fibonacci sequence is definitely not a complex problem to talk about. We all did it in our early stage of programming. So I am not going to explain what it is. Let’s talk about the ways we can generate it in our familiar languages.
When we were just a beginner if anyone asked us to generate this sequence up to nth values, we used to give a big smile and wrote the code using a for loop, right? We all know the way, so let’s skip it too. After a while, we learned about recursion and used recursion to generate the sequence like this,

Here we are using lists and modifying it right? But what if we want to do the same task without modifying any object that means by maintaining immutability? In my previous post, I showed a demo of Stream in Java. Let’s have a look at another demo of it.

One liner right? 😉 Honestly, I never even thought about doing this with one line of code.

Immutability is a mandatory part of functional programming. Is Java functional? Java 8 supports functional programming basically.
How would this code look like in a functional language like Scala?

But Scala also supports imperative programming, right? So what about a purely functional language like Erlang? Run this code 😉


Thanks for reading this. Here is a bonus code of Python for the same purpose.


Facebook Comments

Leave a Comment.