/
GettingStarted.scala
56 lines (49 loc) · 1.08 KB
/
GettingStarted.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// 第2章の演習問題を自分で問いてみる
//
object MyModule{
def fib(n: Int): Int = n match {
case 0 => 0
case 1 => 1
case n => fib(n-1) + fib(n-2)
}
def factorial(n: Int): Int = {
@annotation.tailrec
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n-1, n*acc)
go(n, 1)
}
def sum(n: Int): Int = {
@annotation.tailrec
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n-1, n+acc)
go(n, 0)
}
/*
private def formatSum(x: Int) = {
val msg = "The total sum value of %d is %d"
msg.format(x, sum(x))
}
*/
def abs(n: Int): Int =
if (n < 0) -n
else n
/*
private def formatAbs(x: Int) = {
val msg = "The absolute value of %d is %d"
msg.format(x, abs(x))
}
*/
def formatResult(name: String, n: Int, f: Int => Int) = {
val msg = "The %s of %d is %d."
msg.format(name, n, f(n))
}
def main(args: Array[String]): Unit =
//println(formatAbs(-321))
//println(formatSum(10))
println(formatResult("total sum", 10, sum))
println(formatResult("factorial", 5, factorial))
println(formatResult("Fibonacci", 5, fib))
}