

















Learn Scala  
Getting Started
Books
Specs
Get in the Loop An example To start with, here's a short Scala program that solves the first problem of Project Euler : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
object Euler1 { def dividableBy3or5 (n: int): boolean = (n % 3 == 0  n % 5 == 0) def main (args: Array[String]) { var sum = 0 for (i < 1 to Integer.parseInt(args(0))1) { if (dividableBy3or5(i)) sum += i } println("sum of multiples of 3 and 5 until "+args(0)+" = "+sum) } } More examples Scala is particularly well suited for problems that are defined recursively, or that can solved by recursive algorithms. Here are functions that calculate the factorial of a number (n!) and the numbers of the Fibonacci sequence. def factorial (x: int): BigInt = if (x == 0) 1 else x * factorial(x  1) def fibonacci (n: int): int = if (n == 0) 0 else if (n == 1) 1 else fibonacci(n1) + fibonacci(n2)This recursive "fibonacci" code is considered a "natural" implementation as it mirrors the mathematical definition of the function very closely. However this recursive version is very inefficient, and will become slow very quickly for growing n. Consequently it is not unusual in functional languages to replace inefficient recursive functions with equivalent tail recursive versions. Here is a tail recursive version of "fibonacci": def fibonacci(n: Int) = { // Fn = Fn1 + Fn2 def fib(fn_1: Int, fn_2: Int, i: Int): Int = if (i == 0) fn_2 else fib( (fn_1 + fn_2), fn_1, i  1 ) // tail recursion fib( 1, 0, n ) }With this version the Scala compiler can detect the tail recursion and perform tail call optimization. The generated byte code will be no more inefficient than the code that is generated from the following imperative version. def fibonacci (n: Int) = { var fn_1 = 1 var fn_2 = 0 var i = n while(i > 0) { val prevn_1 = fn_1 fn_1 = fn_1 + fn_2; fn_2 = prevn_1; i = i  1 } fn_2 } CategoryLearnSomethingNew ScalaFaq 