Week 1 Code Snippets

Scala Block Syntax

Scala provides several ways of defining code blocks.

Factorial with Java-like Curly-brace Conditional Block

The return keyword is optional and typically omitted in Scala code; below is an implementation of fact from Scala Introduction - Slide 10 with explicit block curly braces and return.

def fact(n:Int) : Int = {
  println("called with n=%d".format(n))
  if n <= 1 then {
    println("no recursive call")
    return 1 
  } else {
    println("making recursive call")
    return n * fact(n - 1)
  }
}

Void vs Unit

// a method that has no useful result, similar to void producesNothing() { }
def producesNothing() : Unit =
  () // return the only instance of type Unit
end producesNothing

Expression Sequences

def conditional(n: Int) = 
  if n>=5 then
    1 // evaluated for side-effect: there is none -> compiler warning/error
    2 // evaluated for side-effect: there is none -> compiler warning/error
    3 // evaluated for its side-effect and value
  else
    4  // evaluated for side-effect: there is none -> compiler warning/error
    5 // evaluated for its side-effect and value
  end if
end conditional

Conditional Expression

Conditional expressions, like any other expression, evaluate to values, which can be used in further calculations or as items in containers.

def conditionalEntry(n: Int) = 
  val x = 5 * (if n>=0 then 1 else -1)
  List(
    (if n>=0 then 1 else -1),
    2,
    3
  )
end conditionalEntry

Fibonacci Implementations

object fibonacci:

  // int fib(int n) { ... }
  def fib(n: Int) : BigInt = 
    assert (n >= 0)
    if n <= 1 then 
      n
    else 
      fib(n-1) + fib(n-2)
  end fib

  def fibList(n: Int) : List[BigInt] =
    assert (n >= 1)
    if n <= 1 then List(0, 1) // 0 :: 1 :: Nil
    else
      val l: List[BigInt] = fibList(n-1)
      val p: List[BigInt] = l.takeRight(2)
      l :+ (p(0) + p(1))
      // l ++ List(p(0) + p(1))
    end if
  end fibList

  def main(args: Array[String]) = 
    var n = Integer.parseInt(args(0)) // uses Java library
    //println("fib(" + n + ") = " + fib(n))
    println(s"fib($n) = ${fib(n)}") // uses string interpolation
  end main

end fibonacci