19 // In contrast, say we have a pretty expensive operation: |
19 // In contrast, say we have a pretty expensive operation: |
20 |
20 |
21 def peop(n: BigInt): Boolean = peop(n + 1) |
21 def peop(n: BigInt): Boolean = peop(n + 1) |
22 |
22 |
23 val a = "foo" |
23 val a = "foo" |
24 val b = "foo" |
24 val b = "bar" |
25 |
25 |
26 if (a == b || peop(0)) println("true") else println("false") |
26 if (a == b || peop(0)) println("true") else println("false") |
27 |
27 |
28 // This is called "lazy evaluation": |
28 // This is called "lazy evaluation": |
29 // you delay compuation until it is really |
29 // you delay compuation until it is really |
30 // needed. Once calculated though, the result |
30 // needed. Once calculated though, the result |
31 // does not need to be re-calculated. |
31 // does not need to be re-calculated. |
32 |
32 |
33 // A useful example is |
33 // A useful example is |
|
34 |
34 def time_needed[T](i: Int, code: => T) = { |
35 def time_needed[T](i: Int, code: => T) = { |
35 val start = System.nanoTime() |
36 val start = System.nanoTime() |
36 for (j <- 1 to i) code |
37 for (j <- 1 to i) code |
37 val end = System.nanoTime() |
38 val end = System.nanoTime() |
38 f"${(end - start) / (i * 1.0e9)}%.6f secs" |
39 f"${(end - start) / (i * 1.0e9)}%.6f secs" |
154 (for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) #::: |
155 (for (r1 <- rs; r2 <- rs) yield SEQ(r1, r2)) #::: |
155 (for (r1 <- rs) yield STAR(r1)) ) |
156 (for (r1 <- rs) yield STAR(r1)) ) |
156 |
157 |
157 |
158 |
158 enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(200).force |
159 enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(200).force |
159 enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(5000000) |
160 enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))).take(5_000_000) |
160 |
161 |
161 |
162 |
162 val is = |
163 val is = |
163 (enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))) |
164 (enum(LazyList(ZERO, ONE, CHAR('a'), CHAR('b'))) |
164 .dropWhile(depth(_) < 3) |
165 .dropWhile(depth(_) < 3) |
165 .take(10).foreach(println)) |
166 .take(10).foreach(println)) |
|
167 |
166 |
168 |
167 |
169 |
168 // Polymorphic Types |
170 // Polymorphic Types |
169 //=================== |
171 //=================== |
170 |
172 |
536 // language is deep. |
538 // language is deep. |
537 // |
539 // |
538 // http://scalapuzzlers.com |
540 // http://scalapuzzlers.com |
539 // |
541 // |
540 // http://www.latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/ |
542 // http://www.latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/ |
|
543 |
|
544 val two = 0.2 |
|
545 val one = 0.1 |
|
546 val eight = 0.8 |
|
547 val six = 0.6 |
|
548 |
|
549 two - one == one |
|
550 eight - six == two |
|
551 |
|
552 |
|
553 |
541 |
554 |
542 List(1, 2, 3).contains("your cup") |
555 List(1, 2, 3).contains("your cup") |
543 |
556 |
544 |
557 |
545 // I like best about Scala that it lets me often write |
558 // I like best about Scala that it lets me often write |