Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
fp:lab01 [2022/02/14 16:20]
pdmatei
fp:lab01 [2022/02/24 11:47] (current)
pdmatei
Line 13: Line 13:
   * 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]]).   * 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: Integer, a: Integer): Integer = ??? 
- 
-  // computes the nth estimation of sqrt(a) 
-  def nth_guess(n:​ Integer, a: Integer): Integer =  
-     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:​ Integer, a: Integer): Boolean = ??? 
-</​code>​