equal
deleted
inserted
replaced
12 |
12 |
13 |
13 |
14 List(7,2,3,4,5,6).find(_ < 4) |
14 List(7,2,3,4,5,6).find(_ < 4) |
15 List(5,6,7,8,9).find(_ < 4) |
15 List(5,6,7,8,9).find(_ < 4) |
16 |
16 |
|
17 |
|
18 // Values in types |
|
19 // |
|
20 // Boolean: |
|
21 // Int: |
|
22 // String: |
|
23 // |
|
24 // Option[String]: |
|
25 // |
|
26 |
|
27 |
17 val lst = List(None, Some(1), Some(2), None, Some(3)) |
28 val lst = List(None, Some(1), Some(2), None, Some(3)) |
18 |
29 |
19 lst.flatten |
30 lst.flatten |
20 |
31 |
21 Some(1).get |
32 Some(1).get |
35 for (x <- lst) yield x.getOrElse(0) |
46 for (x <- lst) yield x.getOrElse(0) |
36 |
47 |
37 |
48 |
38 |
49 |
39 |
50 |
40 // error handling with option (no exceptions) |
51 // error handling with Option (no exceptions) |
41 // |
52 // |
42 // Try(something).getOrElse(what_to_do_in_an_exception) |
53 // Try(something).getOrElse(what_to_do_in_an_exception) |
43 // |
54 // |
44 import scala.util._ |
55 import scala.util._ |
45 import io.Source |
56 import io.Source |
70 // |
81 // |
71 // In Java, if you didn't write this function, you'd have to depend on |
82 // In Java, if you didn't write this function, you'd have to depend on |
72 // the Javadoc of the get_me_an_int. If you didn't look at the Javadoc, |
83 // the Javadoc of the get_me_an_int. If you didn't look at the Javadoc, |
73 // you might not know that get_me_an_int could return a null, and your |
84 // you might not know that get_me_an_int could return a null, and your |
74 // code could potentially throw a NullPointerException. |
85 // code could potentially throw a NullPointerException. |
|
86 |
|
87 |
|
88 |
|
89 // even Scala is not immune to problems like this: |
|
90 |
|
91 List(5,6,7,8,9).indexOf(7) |
|
92 |
|
93 |
75 |
94 |
76 |
95 |
77 |
96 |
78 // Type abbreviations |
97 // Type abbreviations |
79 //==================== |
98 //==================== |
297 def sum_cubes(lst: List[Int]) = sumOf(x => x * x * x, lst) |
316 def sum_cubes(lst: List[Int]) = sumOf(x => x * x * x, lst) |
298 |
317 |
299 sum_squares(lst) |
318 sum_squares(lst) |
300 sum_cubes(lst) |
319 sum_cubes(lst) |
301 |
320 |
302 def fact(n: Int): Int = |
321 // lets try it factorial |
303 if (n == 0) 1 else n * fact(n - 1) |
322 def fact(n: Int): Int = ... |
304 |
323 |
305 def sum_fact(lst: List[Int]) = sumOf(fact, lst) |
324 def sum_fact(lst: List[Int]) = sumOf(fact, lst) |
306 sum_fact(lst) |
325 sum_fact(lst) |
307 |
326 |
308 // Avoid being mutable |
327 // Avoid being mutable |