added assignment 2 ex 2+3

This commit is contained in:
Louis Heredero 2025-03-03 17:04:42 +01:00
parent 17b5c3adeb
commit 31629ac479
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
2 changed files with 49 additions and 0 deletions

12
src/Assignment2/Ex2.sc Normal file
View File

@ -0,0 +1,12 @@
import scala.annotation.tailrec
def sum(f: Int => Double, a: Int, b: Int) = {
@tailrec
def iter(a: Int, acc: Double): Double = {
if (a > b) acc
else iter(a + 1, acc + f(a))
}
iter(a, 0)
}
sum(x => x * x, 3, 5)

37
src/Assignment2/Ex3.sc Normal file
View File

@ -0,0 +1,37 @@
import scala.annotation.tailrec
// 3.1
def product(f: Int => Double)(a: Int)(b: Int): Double = {
@tailrec
def iter(i: Int, prod: Double): Double =
if (i > b) prod
else iter(i + 1, prod * f(i))
iter(a, 1)
}
product(x => x)(3)(5)
// 3.2
def factorial(n: Int): Double = product(i => if (i == 0) {1} else {i})(0)(n)
factorial(5)
// 3.3
def mapReduce(red: (Double, Double) => Double)(v0: Double)(f: Int => Double)(a: Int)(b: Int) = {
@tailrec
def iter(i: Int, acc: Double): Double =
if (i > b) acc
else iter(i + 1, red(acc, f(i)))
iter(a, v0)
}
val sum = mapReduce((a, b) => a + b)(0) _
val prod = mapReduce((a, b) => a * b)(1) _
sum(i => i)(1)(5)
prod(i => i)(1)(5)
mapReduce((a, b) => a + b)(0)(i => 2 * i + 1)(1)(5)