This is an old revision of the document!


Introduction to Scala

Installation

Scala can be downloaded and installed on either a Windows or NIX platform (e.g. Linux, OS-X) here. For this lecture you must install Scala 3, and we recommend installing it using Coursier (see the previous link)

IDE

One of the most widely used IDE (Integrated Development Environment) for Scala is:

  • alternatively, you can use Sublime, which is a simpler (faster) editor. You can add syntax highlighting plugins for Scala (see: scalameta ), as well as worksheet/REPL support (see: SublimeREPL).

Consider the following code:

def fact(n: Integer): Integer =
  if (n == 1) 1
  else n*fact(n-1)

The function fact is not tail recursive and will quickly fill the call stack. Starting from the code stub below, implement a tail-recursive factorial:

def fact (n: Integer): Integer = {
   def aux_fact(n: Integer, acc: Integer): Integer = 
       if (???) acc
       else ???
   aux_fact(n,1)
}
  • Video (Newton's Square Root solution)

A very fast way to numerically compute $ \sqrt{a}$ , is using Newton's Square Root approximation:

  • Start with $ x_0 = 1$ .
  • Compute $ x_{n+1} = \displaystyle\frac{1}{2}(x_n+\frac{a}{x_n})$

Implement the following function:

  //given a guess x_n, it computes x_{n+1}
  def improve(xn: Integer, a: Integer): Integer = ???
 
  // computes the nth estimation of sqrt(a)
  def nth_guess(n: Integer, a: Integer): Integer = 
     if (n == 0) ???
     else ???

Note that nth_guess will return a more accurate estimation for smaller a, than for larger a's. We may waste a lot of iterations on small numbers, and spend insufficient ones on large numbers. Thus, instead of nth_guess, implement acceptable(xn,a) which returns true iff $ \mid x_n^2 - a \mid \leq 0.001$ . (Hint, google the abs function in Scala. Don't forget to import scala.math._).

  def acceptable(xn: Integer, a: Integer): Boolean = ???