Edit this page Backlinks This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Introduction to Scala ====== ===== Scala setup ===== ==== Installation ==== **Scala** can be downloaded and installed on either a Windows or NIX platform (e.g. Linux, OS-X) [[https://www.scala-lang.org/download/|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: * [[https://www.jetbrains.com/idea/download/ | IntellIJ]] * alternatively, you can use [[https://www.sublimetext.com/download | Sublime]], which is a simpler (faster) editor. You can add syntax highlighting plugins for Scala (see: [[https://scalameta.org/metals/docs/editors/sublime/ | scalameta ]]), as well as worksheet/REPL support (see: [[https://packagecontrol.io/packages/SublimeREPL | SublimeREPL]]). ===== Online exercises ===== Consider the following code: <code scala> def fact(n: Integer): Integer = if (n == 1) 1 else n*fact(n-1) </code> 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: <code scala> def fact (n: Integer): Integer = { def aux_fact(n: Integer, acc: Integer): Integer = if (???) acc else ??? aux_fact(n,1) } </code> ===== Homework - Newton's Square Root method ===== * Video (Newton's Square Root solution) A very fast way to numerically compute $math[\sqrt{a}], is using Newton's Square Root approximation: * Start with $math[x_0 = 1]. * Compute $math[x_{n+1} = \displaystyle\frac{1}{2}(x_n+\frac{a}{x_n})] Implement the following function: <code scala> //given a guess x_n, it computes x_{n+1} def improve(xn: Double, a: Double): Double = ??? // computes the nth estimation of sqrt(a) def nth_guess(n: Double, a: Double): Double = if (n == 0) ??? else ??? </code> 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 $math[\mid x_n^2 - a \mid \leq 0.001]. (Hint, google the ''abs'' function in Scala. Don't forget to import ''scala.math._''). <code scala> def acceptable(xn: Double, a: Double): Boolean = ??? </code>