130 /* boolean operators |
130 /* boolean operators |
131 |
131 |
132 == equals |
132 == equals |
133 ! not |
133 ! not |
134 && || and, or |
134 && || and, or |
135 |
|
136 */ |
135 */ |
137 |
136 |
138 |
137 |
139 def fact2(n: BigInt): BigInt = |
138 def fact2(n: BigInt): BigInt = |
140 if (n == 0) 1 else n * fact2(n - 1) |
139 if (n == 0) 1 else n * fact2(n - 1) |
141 |
140 |
142 fact2(150) |
141 fact2(150) |
143 |
142 |
|
143 |
144 def fib(n: Int): Int = |
144 def fib(n: Int): Int = |
145 if (n == 0) 1 else |
145 if (n == 0) 1 else |
146 if (n == 1) 1 else fib(n - 1) + f(n - 2) |
146 if (n == 1) 1 else fib(n - 1) + fib(n - 2) |
147 |
147 |
148 |
148 |
149 //a recursive function |
149 //gcd - Euclid's algorithm |
150 def gcd(x: Int, y: Int): Int = 2 //??? |
150 |
|
151 def gcd(a: Int, b: Int): Int = |
|
152 if (b == 0) a else gcd(b, a % b) |
|
153 |
|
154 gcd(48, 18) |
|
155 |
151 |
156 |
152 // String Interpolations |
157 // String Interpolations |
153 //======================= |
158 //======================= |
154 |
159 |
|
160 val n = 3 |
|
161 println("The square of " + n + " is " + square(n) + ".") |
|
162 |
|
163 println(s"The square of ${n} is ${square(n)}.") |
|
164 |
|
165 |
|
166 |
|
167 def gcd_db(a: Int, b: Int): Int = { |
|
168 println(s"Function called with ${a} and ${b}.") |
|
169 if (b == 0) a else gcd_db(b, a % b) |
|
170 } |
|
171 |
|
172 gcd_db(48, 18) |
|
173 |
155 |
174 |
156 // Assert/Testing |
175 // Assert/Testing |
157 //================ |
176 //================ |
158 |
177 |
159 // For-Maps (not For-Loops) |
178 // For-Comprehensions (not For-Loops) |
160 //========================== |
179 //==================================== |
161 |
180 |
162 for (n <- (1 to 10).toList) yield square(n) |
181 for (n <- (1 to 10).toList) yield square(n) |
163 |
182 |
164 for (n <- (1 to 10).toList; |
183 for (n <- (1 to 10).toList; |
165 m <- (1 to 10).toList) yield m * n |
184 m <- (1 to 10).toList) yield m * n |
166 |
185 |
167 |
186 |
168 val mtable = for (n <- (1 to 10).toList; |
187 val mult_table = |
169 m <- (1 to 10).toList) yield m * n |
188 for (n <- (1 to 10).toList; |
170 |
189 m <- (1 to 10).toList) yield m * n |
171 mtable.sliding(10,10).mkString("\n") |
190 |
|
191 mult_table.sliding(10,10).mkString("\n") |
|
192 |
|
193 |
|
194 // with patterns |
|
195 |
|
196 for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n |
|
197 |
|
198 for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 |
|
199 |
172 |
200 |
173 |
201 |
174 // Webpages |
202 // Webpages |
175 //========== |
203 //========== |