28 // |
28 // |
29 // Option[Int]: None, Some(0), Some(1), ... |
29 // Option[Int]: None, Some(0), Some(1), ... |
30 // Option[Boolean]: None, Some(true), Some(false) |
30 // Option[Boolean]: None, Some(true), Some(false) |
31 // Option[...]: None, Some(_) |
31 // Option[...]: None, Some(_) |
32 |
32 |
|
33 def div(x: Int, y: Int) : Int = |
|
34 x / y |
|
35 |
33 def safe_div(x: Int, y: Int) : Option[Int] = |
36 def safe_div(x: Int, y: Int) : Option[Int] = |
34 if (y == 0) None else Some(x / y) |
37 if (y == 0) None else Some(x / y) |
35 |
38 |
36 safe_div(10 + 5, 0) |
39 def foo_calculation(x: Int) = |
|
40 if (safe_div(x, x) == None) 24 else safe_div(x, x).get |
|
41 |
|
42 foo_calculation(3) |
|
43 foo_calculation(0) |
|
44 |
|
45 safe_div(10 + 5, 3) |
37 |
46 |
38 List(1,2,3,4,5,6).indexOf(7) |
47 List(1,2,3,4,5,6).indexOf(7) |
39 List[Int]().min |
48 List[Int](3,4,5).min |
40 List[Int](3,4,5).minOption |
49 List[Int]().minOption |
41 |
50 |
42 |
51 |
43 |
52 |
44 // better error handling with Options (no exceptions) |
53 // better error handling with Options (no exceptions) |
45 // |
54 // |
47 // |
56 // |
48 |
57 |
49 import scala.util._ // Try,... |
58 import scala.util._ // Try,... |
50 import io.Source // fromURL |
59 import io.Source // fromURL |
51 |
60 |
52 val my_url = "https://nms.kcl.ac.uk/christian.urban2/" |
61 val my_url = "https://nms.kcl.ac.uk/christian.urban/" |
53 |
62 |
54 Source.fromURL(my_url)("ISO-8859-1").mkString |
63 Source.fromURL(my_url)("ISO-8859-1").mkString |
55 Source.fromURL(my_url)("ISO-8859-1").getLines().toList |
64 Source.fromURL(my_url)("ISO-8859-1").getLines().toList |
56 |
65 |
57 Try(Source.fromURL(my_url)("ISO-8859-1").mkString).getOrElse("") |
66 Try(Source.fromURL(my_url)("ISO-8859-1").mkString).getOrElse("") |
189 |
206 |
190 lst.filter(x => x % 2 == 0) |
207 lst.filter(x => x % 2 == 0) |
191 lst.filter(_ % 2 == 0) |
208 lst.filter(_ % 2 == 0) |
192 |
209 |
193 |
210 |
194 lst.sortWith((x, y) => x < y) |
211 lst.sortWith((x, y) => x > y) |
195 lst.sortWith(_ > _) |
212 lst.sortWith(_ < _) |
196 |
213 |
197 // but this only works when the arguments are clear, but |
214 // but this only works when the arguments are clear, but |
198 // not with multiple occurences |
215 // not with multiple occurences |
199 lst.find(n => odd(n) && n > 2) |
216 lst.find(n => odd(n) && n > 2) |
200 |
217 |
222 def square(x: Int): Int = x * x |
239 def square(x: Int): Int = x * x |
223 |
240 |
224 val lst = (1 to 10).toList |
241 val lst = (1 to 10).toList |
225 |
242 |
226 lst.map(square) |
243 lst.map(square) |
|
244 lst.map(n => square(n)) |
|
245 |
|
246 for (n <- lst) yield square(n) |
|
247 |
227 lst.map(x => (double(x), square(x))) |
248 lst.map(x => (double(x), square(x))) |
228 |
249 |
229 // works also for strings |
250 // works also for strings |
230 def tweet(c: Char) = c.toUpper |
251 def tweet(c: Char) = c.toUpper |
231 |
252 |