This post builds on the same Fibonacci function using the Scala match. match is a Scala implementation of the Java switch statement. Additionally, match is available for all objects instead of just an int, char, byte and short.
Tree Recursion
def fibonacci(num: Int): Int= {
num match {
case 0 => 0
case 1 => 1
case _ => fibonacci(num-1) + fibonacci(num-2)
}
}This should be relatively straightforward right? One new token that appears in this example is the use of _. The underscore in Scala is a wildcard character and in this case example gives us an 'all others' or 'default' to match. The underscore can also be used in your imports.
Java
import java.io.*;
Scala
import java.io._
Functional languages lend themselves toward recursion rather than looping. Our Fibonacci number method is a recursive function but could make better use of the Scala compiler as tail recursion. Tail recursion will optimize the threads needed for each iteration of our method.
Tail Recursion
def fibonacci(num: Int) = fibonacciTR(num, 1, 0)
def fibonacciTR(num: Int, nxt: Int, res: Int): Int= {
num match {
case 0 => res
case _ => fibonacciTR(num-1, nxt+res, nxt)
}
}
The tail recursion is a good deal more gentle than the tree recursion method. In your journeys toward functional programming put aside what you know about iteration and looping and look at how recursion can do the work for you.
1 comments:
The tail recursive version should be pretty optimal.
You can also define the Fibonacci sequence using Scala's Streams (lazy Lists). Check out: http://lamp.epfl.ch/~michelou/activities/teaching/programmationIV/2005/exercises/Fibonacci.html
Scala's Streams are lazy (so you can define an infinite sequence of Fibonacci numbers without computing it all at once, only certain parts as they are needed), and cached (so you never recompute a Fibonacci number).
Post a Comment