|
1 package greeter |
|
2 |
|
3 object Chapter5 { |
|
4 println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet |
|
5 |
|
6 ///////////////////////////////////////////////////////////////////////////// |
|
7 // CHAPTER 5: FIRST-CLASS FUNCTIONS |
|
8 |
|
9 /* |
|
10 // Write a function to sumall integers between two given numbers a and b |
|
11 def sumInts(a: Int, b: Int): Int = |
|
12 if (a > b) 0 else a + sumInts(a + 1, b) |
|
13 |
|
14 sumInts(1, 5) |
|
15 |
|
16 //Write a function to sum the squares of all integers between two given numbers a and b |
|
17 def square(x: Int): Int = x * x |
|
18 def sumSquares(a: Int, b: Int): Int = |
|
19 if (a > b) 0 else square(a) + sumSquares(a + 1, b) |
|
20 |
|
21 square(5) |
|
22 |
|
23 //Write a function to sum the powers 2n of all integers n between two given numbers a and b: |
|
24 def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) |
|
25 def sumPowersOfTwo(a: Int, b: Int): Int = |
|
26 if (a > b) 0 else powerOfTwo(a) + sumPowersOfTwo(a + 1, b) |
|
27 |
|
28 sumPowersOfTwo(2, 4) |
|
29 */ |
|
30 |
|
31 def sum(f: Int => Int, a: Int, b: Int): Int = |
|
32 if (a > b) 0 else f(a) + sum(f, a + 1, b) //> sum: (f: Int => Int, a: Int, b: Int)Int |
|
33 |
|
34 //def sumInts(a: Int, b: Int): Int = sum(id, a, b) |
|
35 //def sumInts(a: Int, b: Int): Int = sum((x: Int) => x, a, b) |
|
36 def sumInts(a: Int, b: Int): Int = sum(x => x, a, b) |
|
37 //> sumInts: (a: Int, b: Int)Int |
|
38 //def sumSquares(a: Int, b: Int): Int = sum(square, a, b) |
|
39 //def sumSquares(a: Int, b: Int): Int = sum((x: Int) => x * x, a, b) |
|
40 def sumSquares(a: Int, b: Int): Int = sum(x => x * x, a, b) |
|
41 //> sumSquares: (a: Int, b: Int)Int |
|
42 def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b) |
|
43 //> sumPowersOfTwo: (a: Int, b: Int)Int |
|
44 |
|
45 def id(x: Int): Int = x //> id: (x: Int)Int |
|
46 def square(x: Int): Int = x * x //> square: (x: Int)Int |
|
47 def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1) |
|
48 //> powerOfTwo: (x: Int)Int |
|
49 |
|
50 // 5.2: Currying |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 } |