Compare commits
2 Commits
17b5c3adeb
...
f66fdac8b4
| Author | SHA1 | Date | |
|---|---|---|---|
|
f66fdac8b4
|
|||
|
31629ac479
|
12
src/Assignment2/Ex2.sc
Normal file
12
src/Assignment2/Ex2.sc
Normal 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
37
src/Assignment2/Ex3.sc
Normal 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)
|
||||
6
src/Lesson2/Curryfication.sc
Normal file
6
src/Lesson2/Curryfication.sc
Normal file
@@ -0,0 +1,6 @@
|
||||
def mul(x: Int, y: Int): Int = x * y
|
||||
|
||||
def mulCurry(x: Int) = (y :Int) => x * y
|
||||
|
||||
def mulCurryScala(x: Int)(y: Int): Int = x * y
|
||||
|
||||
20
src/Lesson2/SumInts.sc
Normal file
20
src/Lesson2/SumInts.sc
Normal file
@@ -0,0 +1,20 @@
|
||||
def sumInts(a: Int, b: Int): Double =
|
||||
if (a > b) 0 else a + sumInts(a + 1, b)
|
||||
|
||||
def sumCubes(a: Int, b: Int): Double =
|
||||
if (a > b) 0 else a * a * a + sumCubes(a + 1, b)
|
||||
|
||||
def sumRec(a: Int, b: Int): Double =
|
||||
if (a > b) 0 else 1.0 / a + sumRec(a + 1, b)
|
||||
|
||||
def mapReduce(f: Int => Double, a: Int, b: Int): Double =
|
||||
if (a > b) 0 else f(a) + mapReduce(f, a + 1, b)
|
||||
|
||||
sumInts(3, 5)
|
||||
sumCubes(1, 3)
|
||||
sumRec(1, 3)
|
||||
|
||||
mapReduce(i => i, 3, 5)
|
||||
mapReduce(i => i*i*i, 1, 3)
|
||||
mapReduce(i => 1.0/i, 1, 3)
|
||||
|
||||
Reference in New Issue
Block a user