Add the first four assignment.
[Scala.git] / Assignment_02 / src / main / scala / Main.scala
1 import scala.annotation.tailrec
2
3 object Main {
4 // Question 1.
5 // a)
6 @tailrec
7 def fac(n: Int, acc: Int = 1) : Int =
8 if (n == 1) acc else fac(n - 1, acc * n)
9
10 // b)
11 def fib(n: Int) : Int = {
12 n match {
13 case 0 => 0
14 case 1 => 1
15 case _ => fib(n - 1) + fib(n - 2)
16 }
17 }
18
19 /*@tailrec
20 def fibTail(n: Int, acc: Int = 0) : Int = {
21 def stage()
22 n match {
23 case 0 => 0
24 case 1 => 1
25 case _ =>
26 }
27 }*/
28
29 // Question 2.
30 def sum(f: Double => Double, a: Int, b: Int): Double = {
31 def iter(a: Int, acc: Double): Double =
32 if (a > b) acc
33 else iter(a + 1, acc + f(a))
34 iter(a, 0.0)
35 }
36
37 // Question 3.
38 def product(f: Double => Double) (a: Int) (b: Int): Double = {
39 def iter(a: Int, acc: Double): Double =
40 if (a > b) acc
41 else iter(a + 1, acc * f(a))
42 iter(a, 1.0)
43 }
44
45 // c)
46 def generalization(init: Double) (reducer: (Double, Double) => Double) (f: Double => Double) (a: Int) (b: Int): Double = {
47 def iter(a: Int, acc: Double): Double =
48 if (a > b) acc
49 else iter(a + 1, reducer(acc, f(a)))
50 iter(a, init)
51 }
52
53 def main(args: Array[String]) = {
54 println("Question 1")
55 println(s"fac(4): ${fac(4)}")
56 println(s"fib(10): ${fib(4)}")
57
58 println("\nQuestion 2")
59 val sumOfSquares = sum(x => x * x, 2, 4)
60 println(s"sum of square from 2 to 4 : $sumOfSquares")
61
62 println("\nQuestion 3")
63
64 def factorial = product (x => x) (1) _
65 println(s"factorial(4) : ${factorial(4)}")
66
67 // def sum2 = generalization (0) ((x, y) => x + y) _ _ _
68 // def product2 = generalization (1) (_ * _) _ _ _
69 }
70 }