Differences

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

Link to this comparison view

Next revision
Previous revision
fp2023:lab02 [2023/03/01 09:16]
pdmatei created
fp2023:lab02 [2024/03/15 10:48] (current)
pdmatei
Line 12: Line 12:
 <code scala> <code scala>
 def fact (n: Int): Int = { def fact (n: Int): Int = {
-   def aux_fact(n: Int, acc: Int): Int = +   def aux_fact(i: Int, acc: Int): Int = 
        if (???) acc        if (???) acc
        else ???        else ???
Line 18: Line 18:
 } }
 </​code>​ </​code>​
 +
  
 **2.2.** Implement a tail-recursive function that computes the greatest common divisor of a natural number: **2.2.** Implement a tail-recursive function that computes the greatest common divisor of a natural number:
Line 24: Line 25:
 def gcd(a: Int, b: Int): Int = ??? def gcd(a: Int, b: Int): Int = ???
 </​code>​ </​code>​
 +
  
 **2.3.** Write a tail-recursive function takes an integer $math[n] and computes the value $math[1 + 2^2 + 3^2 + ... + (n-1)^2 + n^2]. (Hint: use inner functions). **2.3.** Write a tail-recursive function takes an integer $math[n] and computes the value $math[1 + 2^2 + 3^2 + ... + (n-1)^2 + n^2]. (Hint: use inner functions).
Line 33: Line 35:
 **2.4.** Write a function which computes the sum of all natural numbers within a range. Use **two styles** to write this function: direct recursion, and tail recursion. **2.4.** Write a function which computes the sum of all natural numbers within a range. Use **two styles** to write this function: direct recursion, and tail recursion.
 <code scala> <code scala>
-def sumNats(start:​ Int, stop: Int) = ??? +def sumNats(start:​ Int, stop: Int): Int = ??? 
-def tailSumNats(start:​ Int, stop: Int) = ???+def tailSumNats(start:​ Int, stop: Int): Int = ???
 </​code>​ </​code>​
  
-**2.5.** (!) Write a function which takes an initial value $math[x] and a range of values $math[x_0, x_1, \ldots, x_n] and computes $math[x - x_0 - x_1 - \ldots x_n]. Use the most appropriate type of recursion for this task.+**2.5.** (!) Write a function which takes an initial value $math[x] and a range of values $math[x_0, x_1, \ldots, x_n] and computes $math[((x - x_0- x_1- \ldots x_n]. Use the most appropriate ​**type of recursion** for this task.
  
 <code scala> <code scala>
-def subtractRange(x:​ Int, start: Int, stop: Int) = ???+def subtractRange(x:​ Int, start: Int, stop: Int): Int = ???
 </​code>​ </​code>​
  
-**2.6.** (!) Write a function which takes an initial value $math[x] and a range of values $math[x_0, x_1, \ldots, x_n] and computes $math[x_0 - x_1 - \ldots - x_n - x]. Use the most appropriate type of recursion for this task.+**2.6.** (!) Write a function which takes an initial value $math[x] and a range of values $math[x_0, x_1, \ldots, x_n] and computes $math[x_0 - (x_1 - (x_2 - (\ldots - (x_n - x)\ldots )]. Use the most appropriate ​**type of recursion** for this task.