Fibonacci in purely functional immutable Scala

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.

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

The rest of the Explanation is available for subscribers.

or

'Unlimited Scala Algorithms' gives you access to all the Scala Algorithms!

Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.

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.

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

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

Read more

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")

Read more

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))

Read more

Algorithm in Scala

15 lines of Scala (version 2.13), showing how concise Scala can be!

This solution is available for access!

or

'Unlimited Scala Algorithms' gives you access to all the Scala Algorithms!

Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.

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"
)