-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAboutLazySequences.scala
More file actions
executable file
·57 lines (46 loc) · 1.46 KB
/
AboutLazySequences.scala
File metadata and controls
executable file
·57 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package org.functionalkoans.forscala
import support.KoanSuite
class AboutLazySequences extends KoanSuite {
koan("Creating a lazy collection form a strict collection") {
val strictList = List(10, 20, 30)
val lazyList = strictList.view
lazyList.head should be(10)
}
koan("Strict collection always processes its elements but " +
"lazy collection does it on demand") {
var x = 0
def inc = {x += 1; x}
val strictList = List(inc _, inc _, inc _)
strictList.map(f => f).head should be(3)
x should be(0)
strictList.map(f => f).head
x should be(__)
x = 0
val lazyList = strictList.view
lazyList.map(f => f).head should be(__)
x should be(__)
lazyList.map(f => f).head should be(__)
x should be(__)
}
koan("Lazy collection sometimes avoid processing errors") {
val lazyList = List(2, -2, 0, 4).view map { 2 / _ }
lazyList.head should be(__)
lazyList(1) should be(__)
intercept[ArithmeticException] {
lazyList(2)
}
}
koan("Lazy collections could also be infinite") {
val infinite = Stream.from(1)
infinite.take(4).sum should be(__)
Stream.continually(1).take(4).sum should be(__)
}
koan("Always remember tail of a lazy collection is never computed unless required") {
def makeLazy(value: Int): Stream[Int] = {
Stream.cons(value, makeLazy(value + 1))
}
val stream = makeLazy(1)
stream.head should be(__)
stream.tail.head should be(__)
}
}