37 lines
752 B
Scala

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)