# 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

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

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

### Explore the 21 most useful Scala concepts

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

## Register now (free)

Register with GitHub

This gives you access to free test cases & hints for all our 89 published algorithms as well as our installation-free Scala IDE.

You can then choose to subscribe to "Scala Algorithms Unlimited", which gets you access to every current and upcoming algorithm solution. We use Stripe so your data is safe.

We will e-mail you at most once per week with new algorithms and relevant content.
Your data is protected and unsubscribing is straightforward.