Fibonacci numbers (Scala)
From LiteratePrograms
- Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | T-SQL | Visual Basic .NET
The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by
Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.
[edit]
Recursion
The recursive definition can be translated directly into Scala as follows:
<<fibonacci_recursive.scala>>= def fib( n: Int): Int = n match { case 0 => 0 case 1 => 1 case _ => fib( n -1) + fib( n-2) }
[edit]
Iteration
<<fibonacci_iterative.scala>>= def fib( n: Int) = { // initial values var a = 0 // inferred type: Int var b = 1 // inferred type: Int // function next // inferred result type: Pair[Int, Int] def next( a: Int, b: Int) = Pair( b, a + b) ; var i = 0 while( i < n) { // get result pair members by pattern matching val Pair( c, d) = next( a, b) ; // assign result a = c b = d //iterate i = i +1 } // return 'a' a }
[edit]
Tail Recursive
<<fibonacci_tail_recursive.scala>>= def fib( n:Int) = fib_tr( n, 1, 0) def fib_tr( n: Int, b: Int, a: Int): Int = n match { case 0 => a case _ => fib_tr( n -1, a + b, b) }
| Download code |
