# Scala algorithm: Fibonacci in purely functional immutable Scala

Published

## Algorithm goal

The Fibonacci sequence is $$0, 1, 1, 2, 3, 5, 8, 13, 21, ...$$, ie $$F(n + 2) = F(n + 1) + F(n)$$, with $$F(1) = 1$$ and $$F(0) = 1$$.

• $$F(0) = 0$$
• $$F(0) = 1$$
• $$F(2) = F(0) + F(1) = 0 + 1 = 1$$
• $$F(3) = F(1) + F(2) = 1 + 1 = 2$$
• $$F(4) = F(2) + F(3) = 1 + 2 = 3$$
• $$F(5) = F(3) + F(4) = 2 + 3 = 5$$
• $$F(6) = F(4) + F(5) = 3 + 5 = 8$$
• $$...$$

The Fibonacci sequence ("Fibonacci numbers") is hugely important in mathematics, aesthetics and nature.

Goal is to compute it in an immutable and pure-functional fashion in Scala.

## Test cases in Scala

assert(
FibonacciNumbers.take(8).toList.map(_.toInt) ==
List(0, 1, 1, 2, 3, 5, 8, 13)
)
assert(
FibonacciNumbers2.take(8).toList.map(_.toInt) ==
List(0, 1, 1, 2, 3, 5, 8, 13)
)
assert(FibonacciNumbers.apply(2000) > 0, "There is no Stack Overflow")
assert(
FibonacciNumbers2.apply(2000) > 0,
"There is no Stack Overflow with version 2"
)


## Algorithm in Scala

14 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!

## Explanation

We present 2 solutions using LazyList, both of which are stack-safe (Stack Safety).

### First solution using laziness/deferred evaluation

In the first solution, the computation is defined recursively using LazyList - which means the definition of the next item is defined in terms of the recursion. computeFollowing(1, 1) = 1 #:: <lazy sequence of computeFollowing(1 + 1, 1)> = 1 #:: 1 #:: <lazy sequence of computeFollowing(1 + 2, 2)> = ... (this is Â© from www.scala-algorithms.com)

This way of defining it is indeed quite unusual and is a forward-looking computation.

### Second solution using the memoisation property

The second solution is using a different property of LazyLists, which is that they memoise the items (in the previous solution, we do not strictly utilise this property; it could be implemented with an Iterator-like function that does not memoise).

## Scala concepts & Hints

1. ### Def Inside Def

A great aspect of Scala is being able to declare functions inside functions, making it possible to reduce repetition.

def exampleDef(input: String): String = {
def surroundInputWith(char: Char): String = s"$char$input\$char"
surroundInputWith('-')
}

assert(exampleDef("test") == "-test-")


It is also frequently used in combination with Tail Recursion.

2. ### Lazy List

The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').

3. ### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

assert("Hello World".collect {
case character if Character.isUpperCase(character) => character.toLower
} == "hw")

4. ### Zip

'zip' allows you to combine two lists pair-wise (meaning turn a pair of lists, into a list of pairs)

It can be used over Arrays, Lists, Views, Iterators and other collections.

assert(List(1, 2, 3).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6, 3 -> 7))

assert(List(1, 2).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6))

assert(List(5, 6).zipWithIndex == List(5 -> 0, 6 -> 1))

assert(List(5, 6).zipAll(List('A'), 9, 'Z') == List(5 -> 'A', 6 -> 'Z'))

assert(List(5).zipAll(List('A', 'B'), 1, 'Z') == List(5 -> 'A', 1 -> 'B'))


# Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

## How our 100 algorithms look

1. A description/goal of the algorithm.
2. An explanation with both Scala and logical parts.
3. A proof or a derivation, where appropriate.
4. Links to Scala concepts used in this specific algorithm, also unit-tested.
5. An implementation in pure-functional immutable Scala, with efficiency in mind (for most algorithms, this is for paid subscribers only).
6. Unit tests, with a button to run them immediately in our in-browser IDE.

### Study our 100 Scala Algorithms: 6 fully free, 100 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

### Explore the 22 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

## Subscribe to Scala Algorithms

Maximize your Scala with disciplined and consistently unit-tested solutions to 100+ algorithms.

Use it from improving your day-to-day data structures and Scala; all the way to interviewing.