官术网_书友最值得收藏!

View

View has been reimplemented in the new version of the library. Now it represents a reified Iterator operations.

Reification is the process by which an abstract idea about a computer program is turned into an explicit data model or other object created in a programming language (https://en.wikipedia.org/wiki/Reification_(computer_science)).

This means that the Iterator methods are represented as a subclasses of View and encapsulate transformations to apply. The evaluation happens at the moment the view is converted to the strict collection type, or traversed, for example using the foreach method. Views don't remember the type of the source collection. This can be demonstrated by the following example. First, we define a generic transformation that might be strict or lazy, depending on the type of the collection given as an argument:

def transform[C <: Iterable[Char]](i: C): Iterable[Char] = i 
map { c => print(s"-$c-"); c.toUpper }
take { println("\ntake"); 6 }

Next, for each transformation step, we print out its result in the console at the moment the step happens. Now we can compare lazy and strict collection behaviors:

val str = "Scala 2.13"
val view: StringView = StringView(str)
val transformed = transform(view) // A
val strict = transform(str.toList) // B
print("Lazy view constructed: ")
transformed.foreach(print) // C
print("\nLazy view forced: ")
println(transformed.to(List)) // D
println(s"Strict: $strict") // E

This snippet produces the following output in the REPL:

take
-S--c--a--l--a-- --2--.--1--3-
take
Lazy view constructed: -S-S-c-C-a-A-l-L-a-A- -
Lazy view forced: -S--c--a--l--a-- -List(S, C, A, L, A, )
Strict: List(S, C, A, L, A, )

In the first line, we can see that the take method is always evaluated strictly regardless of the underlying collection typethis is commented as A in the preceding code. The second and third lines show the strict evaluation for List[Char], line B in the code. Lines 4 and 5 demonstrate that View[Char] is then evaluated twice, each time at the moment it is forced, once by calling foreach (line C) and once by converting it to the List (line D). Also interesting is that map is only applied to the results of the take method even given the fact that map is the first transformation step in the chain.

主站蜘蛛池模板: 博兴县| 石棉县| 江都市| 长海县| 怀柔区| 连州市| 新昌县| 望都县| 彭州市| 正定县| 惠州市| 宣武区| 大英县| 江华| 海宁市| 隆回县| 平江县| 腾冲县| 文安县| 平和县| 砚山县| 册亨县| 神木县| 大港区| 彩票| 财经| 黔西县| 金沙县| 婺源县| 穆棱市| 苏尼特右旗| 上饶市| 互助| 越西县| 张家界市| 三门峡市| 新巴尔虎左旗| 屏东市| 定西市| 罗定市| 铅山县|