# 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

### Def Inside Def

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

It is also frequently used in combination with Tail Recursion.

### 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').

### Pattern Matching

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

### 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.