1 import scala
.annotation
.tailrec
7 def fac(n
: Int
, acc
: Int
= 1) : Int
=
8 if (n
== 1) acc
else fac(n
- 1, acc
* n
)
11 def fib(n
: Int
) : Int
= {
15 case _
=> fib(n
- 1) + fib(n
- 2)
20 def fibTail(n: Int, acc: Int = 0) : Int = {
30 def sum(f
: Double
=> Double
, a
: Int
, b
: Int
): Double
= {
31 def iter(a
: Int
, acc
: Double
): Double
=
33 else iter(a
+ 1, acc
+ f(a
))
38 def product(f
: Double
=> Double
) (a
: Int
) (b
: Int
): Double
= {
39 def iter(a
: Int
, acc
: Double
): Double
=
41 else iter(a
+ 1, acc
* f(a
))
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
=
49 else iter(a
+ 1, reducer(acc
, f(a
)))
53 def main(args
: Array
[String
]) = {
55 println(s
"fac(4): ${fac(4)}")
56 println(s
"fib(10): ${fib(4)}")
58 println("\nQuestion 2")
59 val sumOfSquares
= sum(x
=> x
* x
, 2, 4)
60 println(s
"sum of square from 2 to 4 : $sumOfSquares")
62 println("\nQuestion 3")
64 def factorial
= product (x
=> x
) (1) _
65 println(s
"factorial(4) : ${factorial(4)}")
67 // def sum2 = generalization (0) ((x, y) => x + y) _ _ _
68 // def product2 = generalization (1) (_ * _) _ _ _