Fibonacci in Scala

Published on 15 May 2023 (Updated: 11 April 2026)

Welcome to the Fibonacci in Scala page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

object Fibonacci:

  private val fibs: LazyList[BigInt] =
    BigInt(1) #:: BigInt(1) #:: fibs.zip(fibs.tail).map(_ + _)
    
  private val usage =
    "Usage: please input the count of fibonacci numbers to output"

  def main(args: Array[String]): Unit =
    val output =
      for
        arg <- args.headOption
        n <- arg.toIntOption if n >= 0
      yield
        if n == 0 then ""
        else
          fibs
            .take(n)
            .zipWithIndex
            .map((f, i) => s"${i + 1}: $f")
            .mkString("\n")

    println(output.getOrElse(usage))

Fibonacci in Scala was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.