Strange results when using Scala collections -
I have some tests with the results that I can not quite explain.
Reduce the list of first test filters, maps and 4 elements:
{val counter = new AtomicInteger (0) val l = list (1, 2, 3) , 4) val filtered = l.filter {I = & gt; Counter.incrementAndGet () true} val maps = filtered.map {i = & gt; Counter.incrementAndGet () i * 2} val less = Map.Redos {(a, b) = & gt; Counter.incrementAndGet () a + b} println ("count" + counter. Gate + "and the result is" decreased ") (20 == decreases) Insert (11 == counter.get)} < / Code> I hope the counter increases 11 times: once for each element during filtering, once for mapping each element and three times to add 4 elements. / P>
The result of the wildcard varies:
{val counter = new AtomicInteger (0) val l = list filtered (1, 2, 3, 4) val = l .filter {counter.incrementAndGet () _> 0} Ell map = filtered.map {counter.incrementAndGet} _ * 2} val less = map. Rados {(a, b) => Counter.incrementAndGet () a + b} println ("count" + counter. + "And the result" + is reduced) Put emphasis (20 == decreased) Inserting (5 == counter.get)} I have at least (no code Compiled), but now, the counter has only increased 5 times!
So, question # 1: Why the number of wildcard bar counters is called and how it changes Works?
Then my understanding of my second, related question ideas was that they would execute the works passed by monadic methods independently, but the following codes do not show up.
{val counter = new AtomicInteger (0) val l = Seq (1, 2, 3, 4). View Val filter = l.filter {counter.incrementAndGet () _> Println ("After filter:" + counter.get) Valmap = filtered. Map {counter.incrementAndGet () _ * 2} println ("after map:" + counter.get) val min = map .Rados {(A, B) = & gt; Counter.incrementAndGet () a + b} println ("after reducing:" + counter.get) emphasize println ("numbered" + counter.get + "and the result is" reduced ") (20 == Less) = Counter.get)} Output is: after filter
: 1 after the map: 2 after the low: 5 times 5 And the result is 20 Question # 2: How is the work coming soon?
I am using Scala 2.10
You are probably thinking that
filter {println _> 0} device
Filters {i = & gt; Println i> 0} But the other ideas of Scala are because
< Code> {println; _ & gt; 0 function then interprets it That's what you're doing in the form of a strange way of specifying the function: val p = {println; (I: int) => I & gt; 0} filter (p) that closely
println val temp = (i: int) = & gt; I & gt; 0 / / temporary name, we forgot it! Val P = Temp Filters (P) The way you can imagine, the way you want it does not work much - you only print once (or your case Increase in salary) Both of your problems are related to this.
Ensure that you are using underscore "fill in the parameter" that you have only one expression! If you are using many statements, it is best to stick clearly named params.
Comments
Post a Comment